Explicit std:: Namespace

Why do you use explicit std:: namespace qualifiers in this lesson's code examples instead of 'using namespace std;'?

In this lesson, I use explicit std:: namespace qualifiers for types and objects from the C++ Standard Library, like std::cout and std::string, instead of a using namespace std; statement. There are a few reasons for this:

  1. It makes it clear that these types and objects are from the Standard Library and not from the current project or some other library.
  2. It avoids potential naming conflicts. If your code defines a function or variable with the same name as something in the std namespace, and you have a using namespace std; statement, you'll get a naming conflict. Using explicit std:: avoids this.
  3. It's considered good practice in many codebases and style guides. While using namespace std; can be convenient for small examples or personal projects, it's often discouraged in larger codebases or when writing libraries.

For example, instead of:

#include <iostream>
using namespace std;

int main() {
  string message = "Hello, world!";
  cout << message << endl;
}

I would write:

#include <iostream>

int main() {
  std::string message = "Hello, world!";
  std::cout << message << std::endl;
}

The explicit std:: makes it clear where string, cout, and endl are coming from.

There are situations where a using statement can be appropriate, like within a limited scope such as a function, but for clarity and to promote good habits, I generally avoid using namespace std; in examples.

Namespaces, Includes, and the Standard Library

A quick introduction to namespaces in C++, alongside the standard library and how we can access it

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Why Use Namespaces in C++?
What are the benefits of using namespaces in C++? When should I use them in my code?
Multiple using Statements
Can I have multiple using statements for the same namespace in different scopes? What happens if I do?
Setting Include Paths
How do I set up my compiler to find header files in different directories?
Namespace Aliases
What is a namespace alias and when would I use one?
Header Include Order
Does the order of #include directives matter? If so, what's the correct order?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant