Quiz Entry - updated: 2026.07.06
How do you use a namespace in C++?
Either qualify each name with namespace:: (e.g. std::cout), or bring names into scope with using.
// Option 1: qualify every name
std::cout << "Hello" << std::endl;
std::vector<int> v;
// Option 2: using-declaration (one specific name)
using std::cout;
using std::endl;
cout << "Hello" << endl;
// Option 3: using-directive (the whole namespace)
using namespace std;
cout << "Hello" << endl;
vector<int> v;
Why namespaces exist: they prevent name collisions — two libraries can each have a sort or string without clashing, because each lives in its own namespace.
Best practices:
- Never put
using namespacein a header file (it forces it on everyone who includes the header) - In
.cppfiles either approach is fine - In large projects, explicit
std::is clearer about where a name comes from
Go deeper:
Namespaces — cppreference — declaration,
using, and name-lookup rules.Namespace — Wikipedia — the general concept beyond C++.