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 after return; 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.

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.

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.

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.

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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.