1

Code :

foo()
{
}
int main()
{
   int a=20;
   a = foo(20);
   printf("\n\n\t A : %d",a); // will print zero.
}

Question :

  1. You may notice that there is no return type for foo(). And it is considered as 'int', Why? Why this 'Implicit int' rule? Why the designers of C loved 'int' so much?

  2. foo() doesn't have parameter declaration, it says that it can accept variable number of arguments. So where does passed arguments go? e.g. foo(20) where did 20 go?

  3. in above example printf prints zero, why?


Now, consider :

foo()
{
}
int main()
{
   int a=20;
   a = foo(a);
   printf("\n\n\t A : %d",a); // It'll print 20. 
}
  • Now printf prints 20 why not 0 like earlier?
Roshin Raphel
  • 2,612
  • 4
  • 22
  • 40
VishalDevgire
  • 4,232
  • 10
  • 33
  • 59

1 Answers1

2
  1. This is a historical thing from the original C specification as I understand it. It's still in the spec that if you don't state a return type then it is int. That doesn't mean you should take advantage of it. That's bad style in my books.

  2. Read this: Is it better to use C void arguments "void foo(void)" or not "void foo()"?

  3. What you are observing is undefined behaviour, which is what you get when you use the return value for a function that doesn't return anything.

Community
  • 1
  • 1
paddy
  • 60,864
  • 6
  • 61
  • 103
  • @VishalD You need to learn how to turn the warnings on. If you are using GCC or Clang, `-Wall`. – Pascal Cuoq Mar 10 '13 at 20:58
  • 1
    Re 2: What happens during the execution is that that `main` pushes 20 on the stack as an int argument, then `foo` does not use it, and after `foo` returns, `main` cleans the argument up. – che Mar 10 '13 at 21:01
  • 1
    @che It does not need to be the stack, it depends on the ABI of the compiler. – the busybee Sep 16 '20 at 10:53