Function declaration and definition

Function declaration:

When you write down the all parts of function except body then it is called declaration of function. For example:

int func(int, float);

is a declaration of a function which return type is int, two arguments: int, float. Pay attention, here we just write argument data type without variable name.You can also write as follows:

int func(int x, float y);

Declaration of function will tell the compiler that this function will be used and defined somewhere.

Function definition:

When a function is written including function body then it is called function definition. For example:

int func(int x,int y)
{
     return x+y;
}

Now a question may arise why we need function declaration?
Let us consider the following two example:
Example 1:

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

Example 2:

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

Analysis:
We already know that a c program execute line by line. At first line 1 then line 2 then line 3 and so on. In example1 func() has been defined before main() function. So main() function will recognize this func() and there is no problem. But in example2 func() has been defined after main(). So main function will not recognize func() and there is a problem. So we have to declare a func() first in example2 to let the compiler know that it will be used and defined later. Example2 will be as follows:

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

Next Previous