Lesson 54 +10 XP

Omitting the std Namespace

Omitting the std Namespace

Tutorials often start with a magic line: using namespace std;. What does it really do?

The std namespace

Everything in the Standard Library - string, cout, vector - lives in the std namespace. The proper, full name is std::string.

#include <iostream>
using namespace std;

int main() {
  cout << "Hello" << endl;
  return 0;
}

Here cout is really std::cout. The using namespace std; line says: "if you see an unknown name, go look in std too."

Why tutorials love it

Without it, the same program looks like this:

#include <iostream>

int main() {
  std::cout << "Hello" << std::endl;
  return 0;
}

Shorter, less typing, fewer distractions when you are still learning cout and string.

The caution

using namespace std; drags the entire standard namespace into view. In a big project with many files and libraries, two things named count or list can clash. Professional code usually writes std:: explicitly, or pulls in only what it needs.

using std::cout;   // just cout, nothing else

TL;DR

  • std:: is the namespace prefix for the Standard Library.
  • using namespace std; lets you skip the prefix.
  • It is common in short tutorials and learning code.
  • In big projects, name clashes make explicit std:: safer.