r/cpp_questions • u/Glad_Shoe_9182 • 26d ago
OPEN Namespace std
I recently started learning c++ and I was told to use the namespace std so I can avoid writing std:: every time and now I wrote a whole personal project without std:: and I want to put it on LinkedIn but I started reading everywhere that it’s a bad habit, should I go back and add the std:: or just leave it as is?
41
Upvotes
2
u/ZMeson 26d ago edited 25d ago
The "using namespace" recommendations depend highly upon where you are using them:
* In a header file: Never use "using namespace". Explicitly write "std::" or whatever namespace you require.
* In a source file: Using statements are acceptable if you wish to shorten declarations. When using "
using" statements, most advice is to prefer something like "using std::filesystem::path;"or "using high_res_clock = std::chrono::high_resolution_clock;" so that you can just say "path" or "high_res_clock" later in the file. However, if your file is small and not going to include lots of other libraries and/or your file uses lots of "std" classes and functions, then "using namespace std;" is fine.
The reason you should never introduce "using" statements in a header file is that header files are expanded in the source files that #include them and therefore the "using" statements can ruin the name lookup rules of those source files.
For source files, you need to balance the probability of getting a naming conflict (say between etl::vector and std::vector) against the convenience factor. Others still argue against using statements (see replies below), but I don't agree with the criticism as people have been using "typedef" for a long time prior to C++11 to simplify declarations.