In C++, how does using std::cout; differ from using namespace std;, and why does the second not belong in a header?
answer
- one name versus every name
- a declaration versus a lookup rule
- headers are pasted into includers
- ambiguity appears at the point of use
basics
~20 susing std::cout; declares one name in the current scope; using namespace std; makes every std name visible to unqualified lookup. In a header the directive reaches every file that includes it, so names such as count become ambiguous there.
solid answer
~50 sA **using-declaration** such as `using std::cout;` introduces exactly one name into the scope it appears in and behaves like a local declaration: it can hide an outer name, and it clashes at once with a local of the same name. A **using-directive** such as `using namespace std;` introduces no names; it tells unqualified lookup to treat every member of `std` as if declared in the nearest namespace enclosing both the directive and `std`, which for `std` is always the global namespace. At namespace scope in a header, that rule is pasted into every translation unit that includes the header, for the rest of that file. Any includer with its own `count`, `distance` or `data` then gets an `ambiguous` error at the point of use, far from the cause. Keep directives out of headers; in source files prefer using-declarations or a directive inside a function body.
code
cpp · 12 lines#include <algorithm>
#include <iostream>
#include <vector>
using namespace std; // imagine this line sits in a shared header
int count = 0; // a global the application already had
int main() {
std::vector<int> v{1, 2, 2, 3};
count = static_cast<int>(std::count(v.begin(), v.end(), 2));
std::cout << count << '\n';
}go deeper
Recall the two spellings and what each pulls in: one name for the declaration, the whole namespace for the directive. Say clearly that the directive never belongs at namespace scope in a header.
Explain why: a directive introduces no names, it changes unqualified lookup, so conflicts appear only where an ambiguous name is used, in files that include the header and never chose the directive.
Show you have debugged it: a build that broke when an unrelated header started including algorithm, a count or distance turned ambiguous, and the fix of qualifying names and moving directives into function bodies.
Treat it as a header hygiene rule a team enforces with review and static checks, alongside qualified names in public headers and namespace aliases for long nested namespaces.
## Namespaces in one paragraph A **namespace** is a named scope for declarations. `std::vector` and a project's own `geo::vector` are different entities because their enclosing namespaces differ, and a **qualified name** such as `std::cout` says exactly which one you mean. Writing the qualifier everywhere is safe but verbose, so C++ offers two ways to drop it: the using-declaration and the using-directive. They look alike and behave very differently. ## The using-declaration: one name, as if declared here `using std::cout;` is a **declaration**. It introduces the single name `cout` into the scope where it appears, and from then on that name behaves much like a name declared in that scope: - In a block, it **hides** a same-named entity from an enclosing scope, for example a global `int count`. - If the same scope already declares an unrelated entity with that name, the program is ill-formed at the using-declaration itself; clang reports `target of using declaration conflicts with declaration already in scope`. - It names one thing (all overloads of a function name come along), so the rest of `std` stays out of reach. ## The using-directive: a rule for unqualified lookup `using namespace std;` is a **directive**, and the standard says outright that it does not introduce any names. Instead, during unqualified lookup after the directive, the members of `std` appear as if they were declared in the nearest enclosing namespace that contains both the directive and `std`. At file scope that is the global namespace. Two consequences follow: 1. Nothing conflicts at the directive line. A global `int count` and the function template `std::count` coexist until some expression says plain `count`. 2. At that point lookup finds both, and the use is ambiguous. The error appears wherever the name is used, which may be hundreds of lines and several files away from the directive. A directive may appear at namespace scope or in a block scope, but not in class scope. ## Why a header is the worst place for it `#include` pastes the header's text into the including file. A directive written at namespace scope in `geometry.hpp` therefore applies to every translation unit that includes `geometry.hpp`, directly or through another header, from that point to the end of the translation unit. Nobody who includes the header chose it, and nobody can undo it. ```cpp #include <algorithm> #include <vector> using namespace std; // arrived through a shared header int count = 0; // the application's own global int main() { std::vector<int> v{1, 2, 2, 3}; count = 2; // error: reference to 'count' is ambiguous } ``` Clang lists both candidates, the global `count` and `std::count` from `<algorithm>`. The same trap waits for any short common name in `std`: `distance`, `data`, `size`, `min`, `max`, `hash`, `function`. Whether a given name collides also depends on which standard headers happen to be included, so a build can break after an unrelated header starts including `<algorithm>`. | | `using std::cout;` | `using namespace std;` | |---|---|---| | What it is | a declaration of one name | a lookup rule for a whole namespace | | Names introduced | exactly one (all its overloads) | none | | Conflict with a local of the same name | error at the using-declaration | ambiguity only where the name is used | | Hides an outer name | yes, like any declaration | no | | In a header at namespace scope | still leaks one name to includers | leaks all of `std` to includers | | Allowed in class scope | yes, for base-class members | no | ## What to do instead - In headers, write qualified names: `std::vector<double>`, `std::size_t`. Readers of a header want the exact entity anyway. - In a `.cpp` file, a using-declaration for the few names you use often is the clean middle ground. - A directive inside a function body ends with that block, so its blast radius is one function. It is a reasonable convenience in short source files and tests, and still a bad idea in a header's inline functions. - For long namespaces, a **namespace alias** shortens the qualifier without changing lookup: `namespace fs = std::filesystem;`. The interview answer fits in two lines: a using-declaration declares one name; a using-directive changes how every unqualified name is looked up, and in a header it changes it for people who never asked.
- Is using namespace std; acceptable inside a function body in a .cpp file?Usually yes. A directive in a block scope only affects unqualified lookup inside that block, so its effect ends at the closing brace and never reaches other files. It can still make a name ambiguous within that function if the file also declares a same-named entity, so many teams prefer a few using-declarations even there. The real rule is about headers and namespace scope.
- What happens if a using-declaration names something that clashes with a local declaration in the same scope?The program is ill-formed at the using-declaration itself. Declaring int sort = 0; and then using std::sort; in the same block makes clang report "target of using declaration conflicts with declaration already in scope". That early, local error is one reason using-declarations are easier to live with than directives, whose conflicts surface only where an ambiguous name is used.
- How do you shorten std::chrono::duration_cast without a using-directive?Use a namespace alias such as namespace chr = std::chrono; and write chr::duration_cast, or a using-declaration such as using std::chrono::duration_cast;. An alias changes no lookup rules, it only gives the namespace a shorter name, so it is safe even in a header if it lives inside your own namespace.
- using namespace std copies every std name into the global namespace
- A using-directive in a header only affects code written inside that header
- using std::cout; makes the rest of iostream usable without std::
- The compiler reports the conflict at the using namespace std line
- If it compiles today, a using-directive in a header is harmless