Home > Blockchain >  Extremely basic question about namespaces in c
Extremely basic question about namespaces in c

Time:10-20

using namespace X;
    cout << var;
    using Y::var;
    cout << var;

So say I have a namespace X and a namespace Y that both contain a variable of type int called var. When I say using namespace X; what I imagine happening is if I use some variable that isn't in the global namescope what basically happens is it goes okay I'm gonna look for var in namespace X but now that I also use Y::var what does this exactly mean? Does that just say var is the same as Y::var? But then in that case what's happening with using namespace X does it not even look for var in there because I said I'm using Y::var?

CodePudding user response:

After the using directive

using namespace X;

the compiler uses the unqualified name lookup to find the name var used in the following statement

cout << var;

And due to the using directive it will find the variable var in the namespace X.

This using declaration

using Y::var;

introduces the variable var from the namespace Y in the current scope and the next statement

cout << var;

will use the variable var from the namespace Y.

Here is a demonstration program.

#include <iostream>

namespace X
{
    int var = 1;
}

namespace Y
{
    int var = 2;
}

int main() 
{
    using namespace X;

    std::cout  << "var = " << var << '\n';

    using Y::var;

    std::cout  << "var = " << var << '\n';
}

The program output is

var = 1
var = 2

That is the using declaration that introduces the variable var in the block scope of the function main hides the declaration of the variable var declared in the namespace X.

In fact the below simplified demonstration program in essence behaves similarly as the above program relative to the name lookup.

#include <iostream>

int var = 1;

int main() 
{
    std::cout  << "var = " << var << '\n';

    int var = 2;

    std::cout  << "var = " << var << '\n';
}

CodePudding user response:

Yes, using Y::var; does hide X::var when you ask for var. The former is as-if Y::var were declared in this scope, the latter only influences unqualified lookup.

using ns_name::name;

using-declaration: makes the symbol name from the namespace ns_name accessible for unqualified lookup as if declared in the same class scope, block scope, or namespace as where this using-declaration appears.

Names introduced into a namespace scope by a using-declaration can be used just like any other names, including qualified lookup from other scopes

using namespace ns_name;

using-directive: From the point of view of unqualified name lookup of any name after a using-directive and until the end of the scope in which it appears, every name from ns_name is visible as if it were declared in the nearest enclosing namespace which contains both the using-directive and ns_name.

  • Related