954,184 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Regarding Function Returning a Value.

I have a doubt on function returning a value. Consider the following program snippet.

int add(int a,int b) {
   int c=a+b;
   return;
   }
 
 int main()  {
   int a=10,b=20;
   printf("%d %d %d",a,b,add(a,b));
   return(0);
   }


The above program gives the output as
10 20 30

But the function is not returning any value. According to the K&R C, Section 4.1,

".......there need be no expression afterreturn; in that case, no value is returned to the caller."

I will be grateful if anyone explains the logic behind this cryptic.

Thanks in advance.

Iqbal_h_a
Light Poster
30 posts since Aug 2006
Reputation Points: 51
Solved Threads: 1
 

Your code probably shouldn't compile. add(int, int) is specified to return an int, but doesn't, which should raise a compile time error.

Infarction
Posting Virtuoso
1,580 posts since May 2006
Reputation Points: 683
Solved Threads: 53
 

Compile your code in strict mode. I guess it should be error. Anyways return value in C on x86 is generally eax , where the result of the last calculation often happens to be placed. Maybe that's why you are seeing this result.

Grunt
Junior Poster
152 posts since Jul 2006
Reputation Points: 197
Solved Threads: 12
 
Your code probably shouldn't compile. add(int, int) is specified to return an int, but doesn't, which should raise a compile time error.


You are right. When I compiled in strict mode, it thrown a compilation error. But in normal mode it doesn't and it will act exactly as Grunt's explanation.
Anyway, thank you very much for your quick reply.

Iqbal_h_a
Light Poster
30 posts since Aug 2006
Reputation Points: 51
Solved Threads: 1
 
Compile your code in strict mode. I guess it should be error. Anyways return value in C on x86 is generally eax , where the result of the last calculation often happens to be placed. Maybe that's why you are seeing this result.


Cool explanation and I am cleared with all my doubts and even it has thrown an error when I compiled in strict mode as you expected.
Much appreciated reply:cool:

Iqbal_h_a
Light Poster
30 posts since Aug 2006
Reputation Points: 51
Solved Threads: 1
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You