0

Following code results in an error as it is not considering ::x in global scope.

#include<iostream>
namespace nspace
{
    int x = 2;
}
int main()
{
    using namespace nspace;
    std::cout << ::x; //error: ‘::x’ has not been declared
    return 0;
}

Following code results in output 2 without any compilation error.

#include<iostream>
namespace nspace
{
    int x = 2;
}
using namespace nspace;
int main()
{
    std::cout << ::x; // Outputs 2
    return 0;
}

I was under the impression that if we have using directive within main function vs using directive in global scope, it is same as far as main function is concerned. For main function both should introduce nspace::x in global scope. And both should result in same behaviour. But above code contradicts my understanding.

So if you can point me to some text from standard that clarifies above behaviour then it would be helpful.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • _"I was under the impression that if we have using directive within main function vs using directive in global scope, it is same as far as main function is concerned."_ `::` explicitely qualifies the global scope, which `x` isn't part of. If you omit any namespace qualifiers, it will behave the same with a `using` alias. – πάντα ῥεῖ Mar 16 '21 at 06:12
  • The thing that baffles me is why is x considered in global scope when using directive is placed in global scope (outside main function). – Pandav Patel Mar 16 '21 at 06:18
  • If it baffles you then consider the alternative. If a using directive in a limited scope affected qualified name lookup for names from outer scopes, how could we *ever* resolve name conflicts? – StoryTeller - Unslander Monica Mar 16 '21 at 06:29
  • That makes sense. Seems like my understanding of qualified name lookup was incorrect until this point. It makes sense now. Thanks! – Pandav Patel Mar 16 '21 at 06:48
  • In second case, as ::x is not present in global scope, using namespace directive is considered and hence it then searches in nspace. While in first case, as :: is not present is global scope and there is no using directive in global scope which can be searched, it results in an error. Comment for my future self! :) – Pandav Patel Mar 16 '21 at 06:56

1 Answers1

1

[namespace.qual]/1:

Qualified name lookup in a namespace N additionally searches every element of the inline namespace set of N ([namespace.def]). If nothing is found, the results of the lookup are the results of qualified name lookup in each namespace nominated by a using-directive that precedes the point of the lookup and inhabits N or an element of N's inline namespace set.

In the first case, using namespace nspace; inhabits the block scope inside the main function, so it is not considered.

In the second case, using namespace nspace; inhabits the global namespace scope, so it is considered by lookup in the global scope.

cpplearner
  • 13,776
  • 2
  • 47
  • 72