I have heard using namespace std; is bad practice, and that I should use std::cout and std::cin directly instead.
Why is this? Does it risk declaring variables that share the same name as something in the std namespace?
I have heard using namespace std; is bad practice, and that I should use std::cout and std::cin directly instead.
Why is this? Does it risk declaring variables that share the same name as something in the std namespace?
Using many namespaces at the same time is obviously a recipe for disaster, but using JUST namespace std and only namespace std is not that big of a deal in my opinion because redefinition can only occur by your own code...
So just consider them functions as reserved names like "int" or "class" and that is it.
People should stop being so anal about it. Your teacher was right all along. Just use ONE namespace; that is the whole point of using namespaces the first place. You are not supposed to use more than one at the same time. Unless it is your own. So again, redefinition will not happen.
It doesn't make your software or project performance worse. The inclusion of the namespace at the beginning of your source code isn't bad. The inclusion of the using namespace std instruction varies according to your needs and the way you are developing the software or project.
The namespace std contains the C++ standard functions and variables. This namespace is useful when you often would use the C++ standard functions.
As is mentioned in this page:
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.
And see this opinion:
There is no problem using "using namespace std" in your source file when you make heavy use of the namespace and know for sure that nothing will collide.
Some people had said that is a bad practice to include the using namespace std in your source files because you're invoking from that namespace all the functions and variables. When you would like to define a new function with the same name as another function contained in the namespace std you would overload the function and it could produce problems due to compile or execute. It will not compile or executing as you expect.
As is mentioned in this page:
Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program. Let us take a few examples to understand why this might not be such a good thing
...
Now at a later stage of development, we wish to use another version of cout that is custom implemented in some library called “foo” (for example)
...
Notice how there is an ambiguity, to which library does cout point to? The compiler may detect this and not compile the program. In the worst case, the program may still compile but call the wrong function, since we never specified to which namespace the identifier belonged.
It's case by case. We want to minimize the "total cost of ownership" of the software over its lifespan. Stating "using namespace std" has some costs, but not using it also has a cost in legibility.
People correctly point out that when using it, when the standard library introduces new symbols and definitions, your code ceases to compile, and you may be forced to rename variables. And yet this is probably good long-term, since future maintainers will be momentarily confused or distracted if you're using a keyword for some surprising purpose.
You don't want to have a template called vector, say, which isn't the vector known by everyone else. And the number of new definitions thus introduced in the C++ library is small enough it may simply not come up. There is a cost to having to do this kind of change, but the cost is not high and is offset by the clarity gained by not using std symbol names for other purposes.
Given the number of classes, variables, and functions, stating std:: on every one might fluff up your code by 50% and make it harder to get your head around. An algorithm or step in a method that could be taken in on one screenful of code now requires scrolling back and forth to follow. This is a real cost. Arguably it may not be a high cost, but people who deny it even exists are inexperienced, dogmatic, or simply wrong.
I'd offer the following rules:
std is different from all other libraries. It is the one library everyone basically needs to know, and in my view is best thought of as part of the language. Generally speaking there is an excellent case for using namespace std even if there isn't for other libraries.
Never force the decision onto the author of a compilation unit (a .cpp file) by putting this using in a header. Always defer the decision to the compilation unit author. Even in a project that has decided to use using namespace std everywhere may fine a few modules that are best handled as exceptions to that rule.
Even though the namespace feature lets you have many modules with symbols defined the same, it's going to be confusing to do so. Keep the names different to the extent possible. Even if not using the namespace feature, if you have a class named foo and std introduces a class named foo, it's probably better long-run to rename your class anyway.
An alternative to using namespaces is to manually namespace symbols by prefixing them. I have two libraries I've used for decades, both starting as C libraries, actually, where every symbol is prefixed with "AK" or "SCWin". Generally speaking, this is like avoiding the "using" construct, but you don't write the twin colons. AK::foo() is instead AKFoo(). It makes code 5-10% denser and less verbose, and the only downside is that you'll be in big trouble if you have to use two such libraries that have the same prefixing. Note the X Window libraries are excellent in this regard, except they forgot to do so with a few #defines: TRUE and FALSE should have been XTRUE and XFALSE, and this set up a namespace clash with Sybase or Oracle that likewise used TRUE and FALSE with different values! (ASCII 0 and 1 in the case of the database!) One special advantage of this is that it applies seemlessly to preprocessor definitions, whereas the C++ using/namespace system doesn't handle them. A nice benefit of this is that it gives an organic slope from being part of a project to eventually being a library. In a large application of mine, all window classes are prefixed Win, all signal-processing modules Mod, and so on. There's little chance of any of these being reused so there's no practical benefit to making each group into a library, but it makes obvious in a few seconds how the project breaks into sub-projects.
There's a very simple answer: it's defensive programming. You know that the uses of std::size_t, std::cout, etc., could be made a little easier with using namespace std; - I hope you don't need to be convinced that such a directive has no place in a header! Within a translation unit, however, you might be tempted...
The types, classes, etc., that are part of the std namespace increase with each C++ revision. There are too many potential ambiguities if you relax the std:: qualifier. It is entirely reasonable to relax the qualifier for names within std that you will be using frequently, e.g., using std::fprintf;, or more probably, something like: using std::size_t; - but unless these are already well-understood parts of the language (or specifically, the std wrapping of the C library), just use the qualifier.
When you can use typedef, combined with auto and decltype inferencing, there's really nothing to be gained from a readability / maintainability perspective.
#include <iostream>
using namespace std;
int main() {
// There used to be
// int left, right;
// But not anymore
if (left != right)
std::cout << "Excuse me, WHAT?!\n";
}
So, why? Because it brings in identifiers that overlap commonly used variable names, and lets this code compile, interpreting it to mean if (std::left != std::right).
PVS-Studio can find such an error using the V1058 diagnostic: https://godbolt.org/z/YZTwhp (thank you Andrey Karpov!!).
Pinging cppcheck developers: you might wish to flag this one. It was a doozy.
To be honest, for me, that's like discussing the number of spaces for indentation.
Using directives in headers cause damage. But in C++ files? Maybe if you use two namespaces at once. But if you use one, it's more about style than real efficiency.
Do you know why threads about indentation are so popular? Anyone can say something about it and sound very smart and experienced.
Namespaces are to avoid naming conflicts. C++ is based on C and C has many problems with function and variable names because sometimes functions from different library clashes. So library developer started to prefix their functions with library names like the following:
foo/foo.h:
void libfoo_foo_foo_h_open(); // the name can be weird then even this one!
C++ introduced namespace to solve this problem in an easy way.
Assume you have two libraries named file and window which handles files and windows respectively and the following code:
#include <file.h>
#include <window.h>
using namespace file;
using namespace window;
void open() {
...
}
file.h:
namespace file {
void open(); // What!
}
window.h:
namespace window {
void open(); // Oh no!
}
The above code will surely and certainly fail to compile.
If you don't like type std:: (only 5 characters) you can always do this: (not a good idea in header files)
using s = std;
If you still want to use using namespace std; in your source file then you are inviting that problem and I have to ask you "What is the PURPOSE of a NAMESPACE?".
Why Namespace Std Used?
C++ has a standard library that contains common functionality you use in building your applications like containers, algorithms, etc. If names used by these were out in the open, for example, if they defined a queue class globally, you'd never be able to use the same name again without conflicts. So they created a namespace, std to contain this change.
Reason 1 to not use: Bad Practice
The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type. Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it imports the entirety of the std namespace into the current namespace of the program.
Reason 2 to not use: Compiler Gets Confused
It is okay to import the whole std library in toy programs but in production-grade code, It is bad. using namespace std; makes every symbol declared in the namespace std accessible without the namespace qualifier.
For Example:
Now, let’s say that you upgrade to a newer version of C++, and more new std namespace symbols are injected into your program which you have no idea about. You may already have those symbols used in your program. Now the compiler will have a hard time figuring out whether the symbol declared belongs to your own implementation or from the namespace you imported without any idea. Some compilers throw errors. If you are unlucky, the compiler chose the wrong implementation and compile it which for sure leads to run time crashes.
Namespace pollution Effect:
While this practice is okay for example code, pulling in the entire std namespace into the global namespace is not good as it defeats the purpose of namespaces and can lead to name collisions. This situation is called namespace pollution.
As long as you do not use 'using namespace std' in the header files it should be perfectly normal.
If there are naming conflicts with say boost, then you do not use this statement in the specific .cpp file but still save everybody's eyes and fingers by not repeating 'std::' ten times on every line in other files.
Unfortunately, this is a pure religious matter now and it is easier/more-productive for everybody to follow the establishing pattern of repeating 'std::' over and over again.