1

I am tryting to compile following code with g++ (version 7.5.0)

using namespace nspace;
int main()
{
        return 0;
}

It gives error as follow

$ g++ above_code.cpp 
namespaces_mystery1.cpp:1:17: error: ‘nspace’ is not a namespace-name
 using namespace nspace;
                 ^~~~~~
namespaces_mystery1.cpp:1:23: error: expected namespace-name before ‘;’ token
 using namespace nspace;
                       ^

Above behaviour is what I have expected.

But when I try to compile following code, it compiles fine without error like above.

using namespace std;
int main()
{
        return 0;
}

Why this different behaviour for namespace named std compared to namespace named nspace

1 Answers1

1

The namespace nspace doesn't exist at the point using namespace nspace; is encountered, whereas the std namespace does. The latter could be true due to implicit or explicit inclusion of facets of the C++ standard library, or the compiler itself might even hardcode it.

If you had written

namespace nspace{}

before the using statement, then compilation would succeed.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    I'm pretty certain there is no inclusion going on – StoryTeller - Unslander Monica Jul 13 '20 at 13:18
  • Thanks for the prompt response. But can you please share more light on " implicit or explicit inclusion of facets of the C++ standard library". Because I expected error in first case. But what puzzles me is the second case. – Pandav Patel Jul 13 '20 at 13:19
  • The compiler probably has some implicit `std::` namespace identifiers "baked" into the compiler itself. Probably for intrinsics, such as `std::abs` mapping to an intrinsic assembly instruction rather than being a function call or even an inline function call. – Eljay Jul 13 '20 at 15:12