Search code examples
ccompiler-warningsfunction-declarationinteger-promotion

Why does declaring the same function both with and without parameters not cause compilation errors?


For the code:

int hi(int);
int hi();
int main()
{
    hi(3);
}

I don't get any compilation errors (calling hi(); without arguments does get a compilation error).

I expected that the compiler would complain that the function has already been declared differently. Any idea why this is the behavior?


Solution

  • You can declare the same symbol as many times as you like, and as long as the declarations don't contradict each other, you won't get an error.

    The reason that

    int hi();
    

    doesn't contradict

    int hi(int);
    

    is because a declaration without any arguments at all means that you say you really don't know how many arguments there are or what types they are. That doesn't really contradict the first declaration. And because you already declared hi, the compiler will simply use that declaration.


    As noted in a comment, this will change with the C23 standard. It has adopted the semantics from C++ that no explicit arguments means void, so

    int hi();
    

    will be equivalent to

    int hi(void);
    

    That of course means that the two declarations will be contradicting each other.