Reputation: 189
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;
}
Upvotes: 6
Views: 3263
Reputation: 37914
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;
}
Upvotes: 0
Reputation: 385385
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.
Upvotes: 3