Search code examples
c++namespacesforward-declaration

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()
{
}

Solution

  • [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.