2
#include<stdio.h>
int add(int,int);

main()
{
      int a=2,b=3;
      printf("%d %d %d",a,b,add(a,b));
      getch();
}

int add(int a,int b)
{
     int c;
     c=a+b;     
}

Ok fine this gives me output 2 3 5 ..But for below program

#include<stdio.h>

int add(int,int);

main()
{
      int a=2,b=3;
      printf("%d %d %d",a,b,add(a,b));
      getch();
}

int add(int a,int b)
{
     int c;
     c=a+b;
     c=0;     
}

Still it is giving 2 3 5 as output.. as we have no return statement final statement c=0 not initializing .. it should give 2 3 0 but it is giving 2 3 5 only.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
  • 2
    [This](http://stackoverflow.com/questions/1610030/why-can-you-return-from-a-non-void-function-without-returning-a-value-without-pr) explains it. – R Sahu Mar 31 '14 at 06:36

2 Answers2

5

It's undefined behavior, anything could happen, you can't rely on it.

Probably what happened is, in the function add(), the value of c is calculated, and left in the stack, in the printf() call, what's in that particular address of stack is printed. Again, you can't rely on undefined behavior.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
-1

This is a very good question.

Inside the function add () the expression

c=a+b;

is evaluated In this expression the right hand side has to be evaluated first. So it returns the value of a+b and that value is stored in your return register and that value is finally stored in c.

In the next expression

c=0;

It is just initialising the value of 0 to c. It does not need to return any value. So the value of the return register is still 5.

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39