Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ Proper position for 'using namespace'

Tags:

c++

namespaces

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.

like image 886
Tambo Avatar asked Oct 19 '15 16:10

Tambo


People also ask

How do you use namespaces correctly?

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.

What should be the location of using namespace std?

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.

What should be the location of using namespace std in C code?

“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.

Can you use namespaces in C?

No, C does not have a namespace mechanism whereby you can provide “module-like data hiding”.


1 Answers

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.

like image 183
Shoe Avatar answered Sep 24 '22 00:09

Shoe