C Program compiling despite incorrect number of arguments to function call

Viewed 75

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.

2 Answers

int sum1(); forward declares a function for which the number of parameters and their types is unknown 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

The second problem is that you call sum1 with 2 arguments when the function needs 3 (and you declared it as a function taking an unknown amount of arguments). The function will then pick an int worth of bytes from the stack (most likely) and use that. This corrupts the stack and makes your program have undefined behavior.

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