Pandav Patel
Pandav Patel

Reputation: 82

C++: using directive statement in main function Vs global scope

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.

Upvotes: 0

Views: 133

Answers (1)

cpplearner
cpplearner

Reputation: 15918

[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.

Upvotes: 1

Related Questions