Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two functions declarations share one definition, is this legal?

Another newbie question:

int foo();  // outer foo function
int main() {
    int foo(); // inner foo function
    cout << foo() << endl;
}

int foo() { // one definition
    return 42;
}

From my understanding, an inner declaration of either function or object will hide outer one, if any.
So the above outer foo() and inner foo() should be two distinct functions.
But they are sharing one definition, which seems confusing. Is it legal that two distinct functions share one definition? How about two distinct object variables? (This is C++ question but the syntax seems also fits C.)

Edit:

It is verified that outer and inner foo are the same funciton using pointer to function:

pf_outer = 0x400792

pf_inner = 0x400792

1 Answers

The inner foo is just another forward deceleration of the same foo(). Consider the following example:

 int foo();
 int foo();

 int main() {
     cout << foo() << endl;
 }

 int foo() { // one definition
    return 42;
 }

This will compile and run and there is no ambiguity because the compiler will replace the use of the same function with the same code.

It is fine to re declare functions.

like image 76
Fantastic Mr Fox Avatar answered Dec 07 '25 16:12

Fantastic Mr Fox



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!