Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to anonymous namespace variable if the same variable exists in global

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

like image 479
yanpas Avatar asked Jan 05 '16 00:01

yanpas


1 Answers

You cannot disambiguate between the two ds 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;
}
like image 154
R Sahu Avatar answered Sep 24 '22 02:09

R Sahu