C++ using namespace std
In this page:
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?
#include <iostream>
int main() {
std::cout << "cout lives inside the std namespace" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
using namespace std;
int main() {
cout << "No std:: prefix needed now" << endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <iostream>
#include <string>
using std::string;
int main() {
string name = "Alex";
std::cout << name << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
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
#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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings