What is a namespace in C++? Why not use using namespace std?

A namespace is a named scope for functions, classes and variables. It avoids name clashes between libraries. The standard library is in std.

#include <iostream>

namespace a { int value() { return 1; } }
namespace b { int value() { return 2; } }

int main() {
    std::cout << a::value() << ' ' << b::value() << '\n';
}
Output

1 2

using namespace std; brings every name of std into your scope. In big programs a name like count or distance can clash with your own. It is OK in a small test, but never write it in a header file. Better: using std::cout; or the full std::. See C++ Namespaces.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.