Accessing the variable inside anonymous namespace (c++)

2.9k Views Asked by At

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;
}
2

There are 2 best solutions below

2
Lightness Races in Orbit On BEST ANSWER

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.

6
Trevor Hickey On

You'll have to access it from a function within the anonymous same scope:

#include <iostream>

int x = 10;

namespace
{
    int x = 20;
    int X() { return x; }
}

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
        std::cout << X() << std::endl; // 20, anonymous
        // how can I access the x inside the anonymous namespace?
    }

    return 0;
}