Fluent::Programmer

    Home Blog About
  • Home
  • Blog
  • About

C++ Best Practice #1: Don't simply use: using namespace std; ๐Ÿ‘‹

  • Fluent Programmer
  •   3 min read

Quick summary โ†ฌ  Never try to import the whole std namespace into your program. Namespaces are developed to avoid naming conflicts. But, when we import the whole namespace there is a possibility that this could lead to name conflicts. You can do more harm than more good.

Description

1
using namespace std;

It is okay to import the whole std library in toy programs but in production-grade code, It is bad. using namespace std; makes every symbol declared in the namespace std accessible without the namespace qualifier. Now, letโ€™s say that you upgrade to a newer version of C++ and more new std namespace symbols are injected into your program which you have no idea about. You may already have those symbols used in your program. Now the compiler will have a hard time figuring out whether the symbol declared belongs to your own implementation or from the namespace you imported without any idea. Some compilers throw errors. If you are unlucky, the compiler chose the wrong implementation and compile it which for sure leads to run time crashes.

For example, Consider the below code,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostreeam>
#include "foo.h" \\ Contains the implementation for same_as

using namespace std; \\Bad practice
class semiregular  { }; \\Implemented in foo.h

int main() {
  semiregular  b;
  ............
  cout << "Hello, Congrats.You are on your way to becoming an expert in programming...">>
}

The above code wonโ€™t trigger any compile-time error if compiled with C++17. It may throw an error when compiled with C++20 that the header file is not included. This is because semiregular is a feature implemented in C++20. So itโ€™s always better to be on the safer side by not loading up your program with all the symbols a namespace offer. Instead use the :: annotation and use the full qualifier like std::cout.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <iostreeam>
#include "foo.h" \\ Contains the implementation for same_as

class semiregular  { }; \\Implemented in foo.h

int main() {
  semiregular  b;
  ............
  std::cout << "Hello, Congrats.You are on your way to becoming an expert in programming...">>
}

The above code didnโ€™t load the whole of std so semiregular is not considered to be part of std and it considers the class implemented by us.

Conclusion

Never use โ€œusing namespace std;โ€. This also applies to all the namespaces. There is a possibility for naming conflict.

You may like this

About The Author

Fluentprogrammer doesn't need coffee to program. They run on pure caffeine and lines of code.

Email Newsletter

Table of Contents

  • Description
  • Conclusion
  • You may like this
  • C++
  • Beautiful code series

Unhealthy love with dark corners of C++

Founded by an engineer to help engineers. 2021โ€“2023.

  • About us
  • Privacy policy