I have this piece of code
#include <iostream>
namespace ns{
int a = 10;
}
using namespace ns;
int a = 20;
int main(){
std::cout << a;
}
As per my understanding, when std::cout << a
is evaluated, a
is searched for in main
‘s local scope. If not found, the lookup is performed in the global scope, where a
is found. So, I was simply expecting it to print 20
, but the code doesn’t compile, claiming that
error: reference to 'a' is ambiguous
However, this code works :
#include <iostream>
namespace ns{
int a = 10;
}
using namespace ns;
int a = 20;
int main(){
std::cout << ::a;
}
It prints 20
. Why does this difference arise? Shouldn’t the two codes be equivalent, considering that a
is not defined in main
‘s scope, and the lookup is performed in the global scope in both the cases?