Home > Net >  C Program compiling despite incorrect number of arguments to function call
C Program compiling despite incorrect number of arguments to function call

Time:12-21

I came across a C program as follows:

#include <stdio.h>

int sum1(); //line A

int main()
{
    int a = 2;
    int b = 3;


    int sum = sum1(a, b);  //line B
    printf("Sum: %d\n", sum);
}


int sum1(int a, int b, int c) //line C
{
    int sum = a   b   c;
    printf("%d %d %d\n", a, b, c);
    return sum;
}

I was surprised to see that the program compiles (gcc version 7.5.0) and gives the following as output:

2 3 3
Sum: 8

I can see 2 errors in this snippet:

  1. The number of arguments in function declaration (line A) is not same as in function definition (line C)
  2. Function call (line B) does not specify all 3 arguments needed in function definition (line C).

Compiling the program in C (using g ), does point out the 2 errors as I mentioned.

I am unable to understand how C is able to ignore such errors but am unable to find any documentation regarding the same. Any help in understanding this will be appreciated.

CodePudding user response:

int sum1(); forward declares a function that can take any amount of arguments which is not in conflict with your definition of the function.

The below would however forward declare a function that does not take any arguments which is in conflict with your definition and will most probably result in a compilation error:

int sum1(void); //line A

CodePudding user response:

This is not an error, though the compiler certainly will have issued warnings if you have them turned on. It is generally a good idea to turn on all compiler warnings and pay close attention to them.

Functions with varying number and types of arguments are legal and quite common in C, and can be made without warnings if declared properly.

  • Related