Let's imagine situation:
#include <iostream>
int d =34;
namespace
{
int d =45;
}
int main()
{
std::cout << ::d ;
return 0;
}
Here the output is 34, because ::
means global namespace. But If I comment 3rd line the output is 45, which is strange.
If I use std::cout << d ;
- I get error
s.cxx:12:15: error: reference to ‘d’ is ambiguous
How can I access unnamed_namespace::d in this scenario?
PS: I've read that unnamed namespace is used for static global variables aka visible only in file scope
You cannot disambiguate between the two d
s in main
without the aid of something else.
One way to disambiguate between the two is to create a reference variable in the namespace and then use the reference variable in main
.
#include <iostream>
int d = 34;
namespace
{
int d = 45;
int& dref = d;
}
int main()
{
std::cout << dref << std::endl;
return 0;
}
But then, why confuse yourself with the same variable? If you have the option, use a different variable name in the namespace or give the namespace a name.
namespace
{
int dLocal = 45;
}
int main()
{
std::cout << dLocal << std::endl;
std::cout << d << std::endl;
return 0;
}
or
namespace main_detail
{
int d = 45;
}
int main()
{
std::cout << main_detail::d << std::endl;
std::cout << d << std::endl;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With