Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 640
arye Avatar asked Sep 03 '26 15:09

arye


1 Answers

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.

like image 183
Some programmer dude Avatar answered Sep 06 '26 03:09

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!