c++namespacesglobal-namespace

Should we be teaching beginners to use a global namespace?


NOTE: I am pretty much a beginner myself. This question concentrates on C++ usage, since that is the only language I have experience with.

There seems to be a consensus on Stack Overflow to use using namespace std; in the code examples provided for C++. I originally learned it this way, and was never taught WHY this is a problem later on.

I was just wondering why people have a problem with using the prefix std:: in their example code. It seems capricious to declare a global namespace, especially since many of the questioners copy+paste the code from the example to their IDE. Namespaces are an advanced programming concept, but I think it would be best to prefix std:: and then explain later if beginners ask about it.

Why is it acceptable to teach beginners this usage?


Solution

  • I think the answer is "it doesn't really matter". It's a subtlety that's fairly easy to pick up and correct later.

    Every beginners' programming text I know of makes a lot of simplifications and uses a lot of handwaving to hide a lot of what's going on ("this line is magic. Just type it in, and we'll discuss what it does later").

    Beginners have enough to worry about without having to fully understand everything in their code, and how/why it is bad, so often these simplifications are good things.

    Although in this case I kind of agree with you.

    Adding the std:: prefix wouldn't be a big deal, and it would demystify namespaces quite a bit. using namespace std is actually much harder to explain and understand properly.

    On the other hand, it takes up space and adds noise to the code which should be as concise and clear as possible.