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?

@freely
link
4
edit-2
1M

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;).

@the_tech_beast
creator
link
11M

thank you. I just got too used to using that namespace std.

@freely
link
31M

I don’t blame beginners for using it. So many starter guides show using namespace std; without even explaining it or its pitfalls.

All I can say is to get used to writting std::
It’s not really that much work, and makes it more obvious where some calls are coming from for any readers of your code.

  • 0 users online
  • 2 users / day
  • 2 users / week
  • 2 users / month
  • 10 users / 6 months
  • 362 subscribers
  • 142 Posts
  • 14 Comments
  • Modlog