Search code examples
cargumentsargument-passing

calling function with lesser number of arguments in C?


I strangely found that C allows linking of function where argument list doesn't match:

//add.c
int add(int a, int b, int c) {
    return a + b + c;
}
//file.c
int add (int,int); //Note: only 2 arguments
void foo() {
    add(1,2);
}

I compiled add.c first, then compiled file.c, both got compiled successfully. Strangely, linker didn't give any sort of error or warning, probably the reason is C linker doesn't compare arguments while linking. I'm not 100% sure about it though. Someone please comment on this.

Now, the question is what is the good practice to avoid this situation or get some sort of warning during compilation, because in my project there are lot of functions in different files, and now & then we have to add some extra argument in the function.


Solution

  • C linker doesn't compare arguments while linking.

    That is correct. Unlike C++ linker which considers argument types to be part of a function signature, C linker considers only function names. That is why it is possible to create a situation with undefined behavior simply by supplying a wrong function prototype the way that you show.

    what is the good practice to avoid this situation or get some sort of warning during compilation?

    Always put prototypes of functions that you are intended to share into a header, and include that header from the places where the function is used and the place where the function is defined. This would ensure that compiler issues a diagnostic message. Treat all compiler warnings as errors. C compilers are often rather forgiving, so their warnings usually indicate something very important.