niting112
niting112

Reputation: 2640

Understanding namespace scope in c++

When I run this below code snippet, the output is a is 6. But since I have used namespace n1, which also has variable by name "a", shouldn't the output be a is 5. Am I missing something ?

#include <iostream>

using namespace std;

namespace n1{
    int a = 5;
}

int main(void){
    int a = 6;
    using namespace n1;
    cout<<"a is "<<a<<endl;
    return 0;
}

But if I use fully qualified name in cout i.e cout<<"a is "<<n1::a; the output is as expected i.e. 5. What is the purpose of using namespace ?

Upvotes: 5

Views: 2252

Answers (3)

Dory Zidon
Dory Zidon

Reputation: 10719

when a variable is defined in the local namespace (a in main is in your local namespace) it will prefer it.

So in this case you must tell it (I would like the a from the n1 namespace n1::a) if you remove the a it will work as expected...

Upvotes: 1

JBL
JBL

Reputation: 12907

The using directive is a hint to the compiler for places where it should search the name a.

This way, the name look-up will be done in this order:

  • First search for a in the local scope
  • If a isn't found, search in the namespace n1
  • If there's still no a found, look in the global namespace

Without the using directive you provided, the second step wouldn't be performed.

In your case, as there is actually a variable (but it could be anything, we're talking about names) named a, it doesn't go any further.

Upvotes: 5

Alok Save
Alok Save

Reputation: 206616

The rule is simple:
"Local variables always shadow/hide the variables in other namespaces or global variables with same name."

Within the scope in which local variable a is declared, the using directive has no effect w.r.t the symbol name a. It still does import all the symbol names from namespace n1 within the current scope but the local variable a still hides n1::a. So n1::a is simply not visible and you need to use the fully qualified name for it.

Upvotes: 3

Related Questions