← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 13 of 15

C++ using namespace std

using namespace std brings every name from the std namespace, including string and cout, into scope unqualified, trading a small risk of naming conflicts for shorter, more readable code.

What is the std Namespace?

The standard library's classes and functions, like string, cout, and vector, all live inside a namespace called std, which groups them together and avoids clashing with names defined elsewhere.

Example: What is the std Namespace?

cpp
#include <iostream>

int main() {
	std::cout << "cout lives inside the std namespace" << std::endl;
	return 0;
}

The using namespace std Directive

Writing using namespace std once near the top of a file brings every name from std into the current scope, letting cout, string, and others be written without the std:: prefix afterward.

Example: The using namespace std Directive

cpp
#include <iostream>
using namespace std;

int main() {
	cout << "No std:: prefix needed now" << endl;
	return 0;
}

Avoiding the Prefix for Strings Specifically

Rather than importing the entire std namespace, using std::string alone brings in just the string name, which is a more targeted way to shorten code without pulling in every other std name.

Example: Avoiding the Prefix for Strings Specifically

cpp
#include <iostream>
#include <string>
using std::string;

int main() {
	string name = "Alex";
	std::cout << name << std::endl;
	return 0;
}

Why Avoid using namespace std in Headers

Placing using namespace std inside a header file forces that namespace import onto every file that includes the header, which can cause unexpected naming conflicts far from where the directive was written.

Example: Why Avoid using namespace std in Headers

cpp
#include <iostream>

// A header should never contain "using namespace std;" -- every file that
// includes it would be forced to import the whole namespace too.
int main() {
	std::cout << "Prefer std:: explicitly in headers" << std::endl;
	return 0;
}

Naming Conflicts Without a Prefix

Importing the entire std namespace risks a naming conflict if the program defines its own identifier with the same name as something in std, since the compiler can no longer tell which one is meant.

Example: Naming Conflicts Without a Prefix

cpp
#include <iostream>
using namespace std;

int count = 5; // fine here, but risks colliding with any "count" from std

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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.