Al227
Al227

Reputation: 151

namespace prefix in function body

I just went through a case where i don't need to prefix the namespace within a function that is itself declared within the namespace

Consider this:

namespace fs
{
    void ftest();
    typedef int uint;
}

void fs::ftest()
{
    uint p = 2; // no prefix fs:: needed
}

This actually doesn't really shock me, but i'd like to have some insights : why does in actually work? Obviously this isn't koenig lookup here.

I'm using VS 2013

Upvotes: 1

Views: 557

Answers (1)

Barry
Barry

Reputation: 302757

This is basic unqualified lookup. The relevant rule is in [basic.lookup.unqual]:

A name used in the definition of a function following the function’s declarator-id that is a member of namespace N (where, only for the purpose of exposition, N could represent the global scope) shall be declared before its use in the block in which it is used or in one of its enclosing blocks (6.3) or, shall be declared before its use in namespace N or, if N is a nested namespace, shall be declared before its use in one of N’s enclosing namespaces. [ Example:

namespace A {
    namespace N {
        void f();
    }
}

void A::N::f() {
    i = 5;
    // The following scopes are searched for a declaration of i:
    // 1) outermost block scope of A::N::f, before the use of i
    // 2) scope of namespace N
    // 3) scope of namespace A
    // 4) global scope, before the definition of A::N::f
}

—end example ]

Upvotes: 3

Related Questions