What is the purpose of 'using namespace std' in C++?

cross-posted from: https://lemmy.ml/post/70930

I am learning C++ and in my book using namespace std is written in every program. I understand that std::cout <<"hello"; can be simply written as cout << "hello"; by using namespace std.

Why?

2 points · 3 comments · view on lemmy.world

3 Comments

freely@lemmy.ml · 0 pts · 5y (1 reply)

Most things in the various STD libs are namespaced as to not clash with other programs. using namespace imports everything in a namespace into your current namespace, even for things you didn't include.

It's just a shortcut to write less, and is a bad habit taught to beginners. It can cause name collisions for all sorts of things since it imports all of std, not just the headers you include.

Just don't use it. If you insist, scope your use of using by putting it inside of functions/methods, and specify specific things to import (i.e. using std::string;).

DubioserKerl@feddit.de · 1 pts · 3y

Correct. While using the namespace saves some time when writing (and some space when printing), it may lead to excess time used debugging later when a name clash happens.

The last point might not be a concern for small "toy programs" used for educational purposes. It is still bad style and should be avoided, especially for toy programs used for educational purposes, though.