Search code examples
c++namespaceslanguage-lawyeridentifier

Is it correct to have a variable with the same name as a namespace


Is it correct to do this? :

namespace name {
    int name;
}

void proc(int name)
{
    name::name = name;
}

int main()
{
    int name = name::name;   
    return 0;
}

It works in GCC. But is this OK with standard and other compilers?


Solution

  • Yes this is okay, we need to look at how the scope resolution operator works in this context. If we look at the draft C++ standard section 3.4.3 Qualified name lookup actually has a very similar example, it says (emphasis mine):

    If a :: scope resolution operator in a nested-name-specifier is not preceded by a decltype-specifier, lookup of the name preceding that :: considers only namespaces, types, and templates whose specializations are types. If the name found does not designate a namespace or a class, enumeration, or dependent type, the program is ill-formed.[ Example:

    class A {
    public:
        static int n;
    };
    
    int main() {
        int A;
        A::n = 42; // OK
        A b; // ill-formed: A does not name a type
    }
    

    —end example ]