tags:

views:

132

answers:

4
#include <iostream>

namespace
{
        int a=1;
}

int a=2,b=3;

int main(void)
{
        std::cout<<::a<<::b;
        return 0;
}

I complie it with my g++,but the output is 23, who can explain it? is that a way to get access to the <unnamed> namespace ::a?

+2  A: 

Using unnamed namespaces, this is not possible. Refer the below article

http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/unnamed_namespaces.htm

You have to go for named namespaces.

bdhar
+3  A: 

No, you can't. You can work around it thus:

namespace
{
    namespace xxx
    {
        int a = 1;
    }
}
...
std::cout << xxx::a << ::b;
Marcelo Cantos
+3  A: 

:: in ::a refers to the global namespace. Anonymous namespace should be accessed via just a (or to be more specific, you shouldn't do like this at all)

Viktor Sehr
thank you for help~,i just confused between global namespace and anonymous namespace~
Javran
Comeau and GCC disagree: without the `::` `a` is ambiguous or undefined. There doesn't seem a way to access it, if it is hidden by a global name.
visitor
@visitor: to access the anonymous a or the global a?
Viktor Sehr
If you remove the `::` from the code given by the asker, then the code would just fail to compile (simple `a` can refer to both). Similarly, if you were to remove the global `a`, then both `a` and `::a` would seem to refer to the unnamed `a`. (Sorry, but the answer appears to be just completely wrong.)
UncleBens
UncleBens: I might be wrong, and yes, you can access anonymous a by using both a and ::a, however, altough I dont have the definition here, I am pretty sure that :: is defined to prefer global namespace before anonymous.
Viktor Sehr
A: 

You can access the global namespace, but don't redefine it.

#include <iostream>

namespace
{
        int a=1;
}


int b=3;

int main(void)
{
        std::cout<<::a<<::b;
    return 0;
}

here the out is 13.

Arman