tags:

views:

132

answers:

4
#include<stdio.h>
int add(int,int);
int main()
{
  int p=add(10,20);
  printf("%d",p);
  return 0;
}

int add(int x, int y)
{
  int sum=x+y;
}

O/P: 30

#include<stdio.h>
int add(int,int);
int main()
{
  int p=add(10,20);
  printf("%d",p);
  return 0;
}
int add(int x, int y)
{
  int sum=x+y;
  printf("Hello");
}

O/P: 5

#include<stdio.h>
int add(int,int);
int main()
{
  int p=add(10,20);
  printf("%d",p);
  return 0;
}
int add(int x, int y)
{
  int sum=x+y;
  sum++;
}

O/P: 30
+10  A: 

None of the code snippets would compile because you haven't declared/defined the functions before using them.

Furthermore even if you add the declarations above main() the behaviour of the snippets would still be undefined because you are using the returned value of a non-void function having no return statement.

Prasoon Saurav
Yup, none of the `add` functions actually return anything.
Piskvor
@Prasoon: You can call function without a prototype in C. So you can compile without declaring the function, but will usually get a warning. Nevertheless the functions miss a return statement.
harper
+5  A: 

You aren't returning sum in your add function.

GWW
Sorry I messed up a bit and edited your post instead of mine by mistake. However rolled back your answer. :)
Prasoon Saurav
No worries, your answer is much better anyway :)
GWW
+1  A: 

printf("%d",p); is printing some garbage that p points to. You should return sum from add:

return sum;
Vijay Mathew
+1  A: 

Just by luck, or rather because you compiled them without optimization. ;-)

The results are actually undefined, and depend on the compiler and compilation options. In your setup the function add() happened to leave something on the stack at the place where main() expected a return value. Try with optimization and you will see the difference.

Edgar Bonet