Monday, July 12, 2021

Why is “using namespace std;” considered bad practice?

  1. I've been told by others that writing using namespace std; in code is wrong, and that I should use std::cout and std::cin directly instead.

    Why is using namespace std; considered a bad practice? Is it inefficient or does it risk declaring ambiguous variables (variables that share the same name as a function in std namespace)? Does it impact performance?.

  2. Using-declaration
  3. Introduces a name that is defined elsewhere into the declarative region where this using-declaration appears..

  4. Namespaces (C++)
  5. A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. All identifiers at namespace scope are visible to one another without qualification. Identifiers outside the namespace can access the members by using the fully qualified name for each identifier, for example std::vector <std::string > vec;, or else by a using Declaration for a single identifier (using std::string), or a using Directive for all the identifiers in the namespace (using namespace std;). Code in header files should always use the fully qualified namespace name.

    The following example shows a namespace declaration and three ways that code outside the namespace can accesses their members..

  6. General I heard this somewhere
  7. I read somewhere on this site that someone had written that it's bad practice to use "using namespace std;" in your C++ code.

    Can anyone explain the theory behind this?

No comments:

Post a Comment