I was integrating some C++ in somelse's one and found out we adopt two different strategies regarding the use of using namespace commands.
For cleanliness of source code, which of the two is the most correct solution?
namespace foo
{
using namespace bar;
}
or
using namespace bar;
namespace foo
{
}
Thanks a lot for your help,
T.
Typically, you declare a namespace in a header file. If your function implementations are in a separate file, then qualify the function names, as in this example. A namespace can be declared in multiple blocks in a single file, and in multiple files.
It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program. So the members of the “std” namespace are cout, cin, endl, etc. This namespace is present in the iostream. h header file.
“using namespace std” means we use the namespace named std. “std” is an abbreviation for standard. So that means we use all the things with in “std” namespace. If we don't want to use this line of code, we can use the things in this namespace like this.
No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.
The two are not equivalent. In the first case the namespace bar
is imported in the namespace foo
so for every bar::x
you can access it as foo::x
. In the latter the namespace bar
is imported in the global namespace (or the namespace that wraps both up) and it can be accessed as ::x
.
I'd recommend to always choose the narrowest possible solution for you. Even to the point of including the namespace only in the function you actually need it. So if you are in doubt go with the first one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With