'using namespace std;'

'using namespace std;'
0

#1

Hello,

for all the time I’ve been coding I have always used the line ‘using namespace std;’ at the beginning. I have noticed a lot of criticism against it.

Can I ask why this line of code is frowned upon?

In a console program can you mix seperate classes, some in namespace std and others without it?

And seeing as it considered a bad approach, what is the worst it could do to a simple 2D indie game?


#2

I’m not an c++ expert, but I do coding since 1999 (as my profession). So I try to answer, what I learned about it.

C++ uses namespaces to avoid name clashes. It can be compared to Java and the packages in there. That’s good, because so you can write a function bestFunctionEver (in namespace foo) and I can create a library with bestFunctionEver (in namespace bar). You can use both in you code, with just writing foo::bestFunctionEver or bar::bestFunctionEver.

The command using namespace std will remove the namespace for the std. Consider you are writing your code in foo and have a string class. Because you are within your own namespace, you can call string. It’s fine. Now you set using namespace std. The compiler didn’t know which string class do you want, so you have to write foo::string or std::string.

Your code will compile as normal, but in my opinion it’s better to avoid using namespace for external libraries and to prefix the calls.


#3

For me I just prefix everything with its namespace for my own sanity, others and then the compiler last :slight_smile: lol

std::string

cocos2d::Sprite

SlackmoehrleUtils::writeAGame


#4

It’s only bad if you put the using namespace in your header files, which might be used by any of the implementation files. Putting it at the top of your implementation file is fine, however for the last few years I have not being doing this for std and it seems natural to add std:: for every reference to the STL types.


#5

I use using namespace std so I don’t have to write out std:: every time just a lazy coder :slight_smile: My approach is to keep things simple and easy to code. Stuff like sharing implementation and such I will cross that bridge when it happens. Just keep them back of my mind it might happen later or not.