Olumide
Olumide

Reputation: 5809

Function definition precedes declaration in namespace

The following bit of code, in which a function definition predeeds its declaration, compiles in VS .NET 2008 and Cygwin gcc 4.8.2. Is it legal?

namespace N
{
    int init()      // Definition appears first
    {
        return 42;
    }       
}

namespace N
{
    int init();     // followed by declaration
    const int x = init();
}

int main()
{
}

Edit

I suppose this isn't too different from the following with also compiles

void foo()
{
}

void foo();

int main()
{
}

Upvotes: 2

Views: 114

Answers (2)

Mark B
Mark B

Reputation: 96233

It looks like this is covered by 3.3.1/4:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,

— they shall all refer to the same entity, or all refer to functions and function templates; or

Then 8.3.5/5:

A single name can be used for several different functions in a single scope; this is function overloading (Clause 13). All declarations for a function shall agree exactly in both the return type and the parameter type- list.

This seems to clearly show that you can declare the same function twice, by having the declarations ...agree exactly in both the return type and the parameter type- list.

Upvotes: 1

Columbo
Columbo

Reputation: 60969

[basic.def]/1:

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

It is fine to (re)declare a name at any time given that the declaration is consistent with respect to earlier ones. In this case, it is consistent, as the type of init in both declarations is int(). So yes, the code is well-formed.

Upvotes: 5

Related Questions