Skip to content
Related Articles

Related Articles

Improve Article

What happens when a function is called before its declaration in C?

  • Difficulty Level : Easy
  • Last Updated : 17 Sep, 2021
Geek Week

In C, if a function is called before its declaration, the compiler assumes the return type of the function as int.
For example, the following program fails in the compilation.

C




#include <stdio.h>
int main(void)
{
    // Note that fun() is not declared
    printf("%c\n", fun());
    return 0;
}
 
char fun()
{
   return 'G';
}

if the function char fun() in the above code is defined before main() then it will not compile successfully.  Because the compiler assumes the return type as “int” by default. And at declaration, if the return type is not matching with int then the compiler will give an error.

The following program compiles and run fine because function is defined before main().

C




#include <stdio.h>
 
int fun()
{
   return 10;
}
 
int main(void)
{
    // Note the function fun() is declared
    printf("%d\n", fun());
    return 0;
}

What about parameters? compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems. For example, the following program compiled fine in GCC and produced garbage value as output. 

C




#include <stdio.h>
 
int main (void)
{
    printf("%d", sum(10, 5));
    return 0;
}
int sum (int b, int c, int a)
{
    return (a+b+c);
}

There is this misconception that the compiler assumes input parameters also int. Had compiler assumed input parameters int, the above program would have failed in compilation.
It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run (See this for more details).
Source: 
http://en.wikipedia.org/wiki/Function_prototype#Uses
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.



My Personal Notes arrow_drop_up
Recommended Articles
Page :