user3424826
user3424826

Reputation:

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

Upvotes: 3

Views: 247

Answers (2)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158529

This is perfectly fine to redeclare a function like this, we can see this from draft C++ standard in two places, in section 3.1 Declarations and definitions which says:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.[...]

and goes on to say:

A declaration is a definition unless it declares a function without specifying the function’s body [...]

and in section 13.1 Overloadable declarations paragraph 3 which says:

Parameter declarations that differ only in the use of equivalent typedef “types” are equivalent. A typedef is not a separate type, but only a synonym for another type (7.1.3). [ Example:

 typedef int Int;

 void f(int i);
 void f(Int i); // OK: redeclaration of f(int)
 void f(int i) { /* ... */ }
 void f(Int i) { /* ... */ } // error: redefinition of f(int)

—end example ]

Both declarations will refer to the same definition, you are not allowed to redefine the function.

The function declarations of are also allowed to differ by their outermost cv-qualifiers as well.

Upvotes: 2

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33904

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.

Upvotes: 2

Related Questions