Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is "using namespace std;" considered bad practice?

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?

like image 409
akbiggs Avatar asked Sep 21 '09 03:09

akbiggs


People also ask

Why we should not use using namespace std in C++?

Bad Practice: using namespace std So if we are using that other namespace (with the other cout entity) along with the std namespace, then the compiler will not know which cout to use. As a result, we'll get an error whenever we use cout .

What happens if we don't include using namespace std in our C++ program?

If we don't want to use this line of code, we can use the things in this namespace like this. std::cout, std::endl. If this namespace is not used, then computer finds for the cout, cin and endl etc.. Computer cannot identify those and therefore it throws errors.

Why is it important to have the using namespace std in your programs?

Need of namespace: As the same name can't be given to multiple variables, functions, classes, etc. in the same scope. So to overcome this situation namespace is introduced.


1 Answers

This is not related to performance at all. But consider this: you are using two libraries called Foo and Bar:

using namespace foo; using namespace bar; 

Everything works fine, and you can call Blah() from Foo and Quux() from Bar without problems. But one day you upgrade to a new version of Foo 2.0, which now offers a function called Quux(). Now you've got a conflict: Both Foo 2.0 and Bar import Quux() into your global namespace. This is going to take some effort to fix, especially if the function parameters happen to match.

If you had used foo::Blah() and bar::Quux(), then the introduction of foo::Quux() would have been a non-event.

like image 90
Greg Hewgill Avatar answered Oct 07 '22 00:10

Greg Hewgill