Search code examples
c++staticanonymousunnamed-namespace

Accessing the variable inside anonymous namespace (c++)


I have following code and I don't know how can I access the x inside the anonymous namespace in this setting. Please tell me how?

#include <iostream>

int x = 10;

namespace
{
    int x = 20;
}

int main(int x, char* y[])
{
    {
        int x = 30; // most recently defined
        std::cout << x << std::endl; // 30, local
        std::cout << ::x << std::endl; // 10, global
        // how can I access the x inside the anonymous namespace?
    }

    return 0;
}

Solution

  • You can't!

    You cannot access the namespace's members by its name, because it doesn't have one.
    It's anonymous.

    You can only access those members by virtue of their having been pulled into scope already.