Should I use std::cout or just cout alone

closed account (96b9y60M)
I always here people say use std::cout,but most programs I see use cout without the std. I am really confused, which can I use?
Those are the same thing. The reason you can use cout instead of std::cout is because your program has "using namespace std;" or "using std::cout;" in it.

This general question is actually brought up a lot, and people have opinions on it.
https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice

Here are some other threads that talk about namespaces and std::
http://www.cplusplus.com/forum/beginner/49748/
http://www.cplusplus.com/forum/beginner/177564/
http://www.cplusplus.com/forum/beginner/230234/

tl;dr my view on it is that it's usually fine to use for small programs as long as you know what you're doing, but can lead to really hard-to-discover bugs if you don't know what you're doing. If I use a "using" statement, I personally usually restrict it to being within a function scope.
As C++ evolves (C++20 and beyond), even more symbols are becoming part of the std namespace (e.g. std::size), and this will potentially cause more ambiguity problems in the future for programs that use "using namespace std;"

One thing that is generally agreed upon is that "using namespace std;" should NOT be used in a header file, because by putting in a header file, you are FORCING users of that header file to inject the std namespace into the global namespace.
Last edited on
try using std::cout instead of namespace std
it feels like the best compromise to me.
Last edited on
Starting in C++17, you can also combine using statements snugly into one line. (I think it was Cubbi or somebody that first showed me this, apologies if I misremembered.)

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{
  using std::cout, std::cin, std::string;

  string name;
  cout << "What is your name? ";
  getline(cin, name);
  cout << "Hello, " << name << "!\n";
}
(Doesn't work on cpp.sh because it is still only C++14)
Last edited on
Topic archived. No new replies allowed.