I am starting out with C++ and almost everywhere I see there is these 2 sentences at the top.
#include <iostream>
using namespace std;
As I understand namespaces are something to keep names separate and have same identifiers in different namespaces. So isn't including std
in the beginning undoing all the hard work of creating namespaces? Isn't it better to have something like std::cout
when I need a certain function from a particular namespace?
Would including the namespace in the particular function that uses it a good tradeoff between less typing (std::cout
vs. cout
everywhere) and avoiding the name conflicts(abc in foo and abc in bar avoided using foo::abc
and bar::abc
)? Something like
int function_using_abc_namespace(int a)
{
using namespace abc;
//Rest of the function
}
I wanted to know because avoiding name conflicts is necessary but avoiding more typing is also important. If this isn't good way to get a middle ground then what are the alternatives?
Best Answer
Updated answer based on updated question
It is okay to
using namespace std
in*.cpp
files. It is okay tousing namespace std
inside function bodies.Reason: In both cases, they aren't contagious. Contagiousness is the only reason why they shouldn't be used at the global namespace level in header files.
Single-file C++ projects (having just one
*.cpp
file, no headers, e.g. in programming puzzles and competitive programming) can use them liberally.Original answer
The only hard rule with
using namespace std;
in C++ is this:(*.cpp)
.Other than that, I suggest taking a pragmatic approach to it:
This brings up the question of: what is the true benefit of having namespaces? The simple answer is disambiguation. But disambiguation for who's benefit?
Disambiguation for programmers?
Disambiguation for automated tools, such as compilers, automatic comment-to-documentation generators (Javadoc, Doxygen, etc), and automatic refactoring tools?
Therefore, as long as it does not cause a conflict, feel free to import namespaces.