about namespace using declarations

hi,I want to ask a question about namespace using declarations.
In "C++ primer" ,they all be writen as
1
2
3
4
using std::cin;
using std::cout;
using std::endl;
...

but in our textbook they're
using namespace std;
I just want to know which is better in C++ or which would you prefer?
I prefer to use individual using statements such as:

1
2
3
4
5
6
7
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#include <iomanip>
using std::setw;


I recommend the above for new programmers as it reinforces which header file each is declared in.
closed account (z05DSL3A)
using Declarations, ie:
1
2
3
using std::cout;
using std::cin;
using std::endl

add names to the scope in which they are declared. The effect of this is:
» a compilation error occurs if the same name is declared elsewhere in the same scope;
» if the same name is declared in an enclosing scope, the the name in the namespace hides it.

The using directive, ie using namespace std;, does not add a name to the current scope, it only makes the names accesable from it. This means that:
» If a name is declared within a local scope it hides the name from the namespace;
» a name in a namespace hides the same name from an enclosing scope;
» a compilation error occurs if the same name is made visible from multiple namespaces or a name is made visible that hides a name in the global name space.

So, to my mind, using Declarations are better than using directives.
I would strongly advise against intermixing using declarations with #includes. In Return 0's example above, suddenly iomanip and anything it includes sees std::cout, std::cin, and std::endl in the global namespace which is exactly contrary to the purpose of namespaces.

Only "use" things after all of your #includes.

Topic archived. No new replies allowed.