0

I'm studying c++ namespace and i made a simple code to understand it. In particular i made this code and i don't understand why it doesn't give me the compiler error that i'have already decleare the variable 'a'. Is the compiler help me in some way?

#include<iostream>
using namespace std;
namespace funzioni_e_altro
{
    int a=5;
    int b=20;
    int c=10;
}
int main()
{
    using namespace funzioni_e_altro;
    int a=0;
    cout<<funzioni_e_altro::a<<"\n";
    cout<<b<<"\n";
    cout<<a<<"\n";
 return 0;
}

I expect it gave me a compiler error, but it gave me the outputs:
5
20
0

  • namespace funzioni_e_altro literally traslated from italian to english means functions_and_other – Andrea Goldoni May 11 '19 at 17:30
  • These variables inside the namespace are global. By `int a=0;` you declare new variable, which is 'visible' only in `main` and by calling `a` in `main` you access your new variable in `main`. – J. S. May 11 '19 at 17:31

1 Answers1

1

A using directive makes the names in the namespace available for unqualified name lookup. But it doesn't introduce any new declarations into the block. When you declare a in main it hides the name the using directive could have brought in. That a is no longer considered during unqualified name lookup inside main.

So when you write a in main, it can only refer to the local variable. Same as if there was no using directive present at all in main.

This behavior is intended. It prevents complete an utter chaos from happening. A using directive should not prevent code from declaring a name in its own scope if it needs to. And you may always refer to the variable in the namespace by fully qualifying its name.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458