if using namespace std is not recommended...

Hi,

if using namespace std is not recommended, then why does Mr. Stroustrup himself have codes on his own site that have it? http://www.stroustrup.com/bs_faq2.html

And also, then why does code blocks IDE have it in the standard hello world template that it gives you when you create a new console application project when you're starting a new c++ code?


Just wondering
-- mc0134
Last edited on
Because those are meant for beginners. I personally recommend that beginners use namespace std since it makes you code cleaner looking (not that that actually helps much with most beginners!). Any code I post here will probably have it, but that doesn't mean that I think it's a good idea in a larger program. It's obviously an idiotic idea in a larger program since it can add hundreds and hundreds of extra identifiers into the global namespace (including any that appear in future versions of the language).

On the other hand, it's ridiculously ugly to have std:: all over the place. I always try to minimize it. One thing you can do is using namespace std at the beginning of a function so it is only active in that small scope. Or perhaps better, to have something like:
1
2
3
4
use std::cout;
use std::cin;
use std::vector;
use std::string;

Put is either globally or at the beginning of a function. This way you are adding a selective set of identifiers to the global namespace and not a ton of arbitrary identifiers you don't even intend to use.

Here are a few quotes from Bjarne's book The C++ Programming Language (4th edition).

For simplicity, I will rarely use the std:: prefix explicitly in examples.


It is generally in poor taste to dump every name from a namespace into the global namespace. However, in this book, I use the standard library almost exclusively and it is good to know what it offers. So, I don’t prefix every use of a standard library name with std::.


Often, we like to use every name from a namespace without qualification. That can be achieved by providing a using-declaration for each name from the namespace, but that’s tedious and requires extra work each time a new name is added to or removed from the namespace. Alternatively, we can use a using-directive to request that every name from a namespace be accessible in our scope without qualification.


Using a using-directive to make names from a frequently used and well-known library available without qualification is a popular technique for simplifying code. This is the technique used to access standard-library facilities throughout this book.


Within a function, a using-directive can be safely used as a notational convenience, but care should be taken with global using-directives because overuse can lead to exactly the name clashes that namespaces were introduced to avoid.
Topic archived. No new replies allowed.