Search code examples
cfunctiondeclarationfunction-prototypes

why it is necessary to use semicolon after functions prototype


Why we use a semicolon after the int add(int,int) statement in second line.

#include<stdio.h>
int add(int,int);
int main()
{
int a,b,c;
scanf("%d %d",&a,&b);
c=add(a,b);
printf("The sum of the 2 numbers is %d",c);
return 0;
}
int add(int x,int y)
{
int sum;
sum=x+y;
return sum;
}

Solution

  • In the C grammar declarations are defined the following way

    declaration:
        declaration-specifiers init-declarator-listopt ;
                                                      ^^^ 
    

    As you can see the semicolon is required.

    And this

    int add(int,int);
    

    is a function declaration. Thus you have to place a semicolon at the end of the declaration.

    Compare two programs

    int main( void )
    {
        int add( int x, int y )
    
        {
            //...    
        }
    }
    

    and

    int main( void )
    {
        int add( int x, int y );
    
        {
            //...    
        }
    }
    

    The first program is invalid because the compiler will think that the function add is defined within function main.

    The second program is valid. There is a function declaration and a code block within main.

    So semicolons are needed that to distiguish declarations from other program constructions.