Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ namespaces - "using" or explicitly stated? [duplicate]

Possible Duplicates:
Why is ‘using namespace std;’ considered a bad practice in C++?
Using std Namespace

Is it just a matter of preference? Or is there a valid reason for preferring

using namespace std;
#include <string>
myString string;

or

#include <string>
myString std::string;

I suppose that explicitly stating the namespace each time, while a drag to type, avoids any possibility of name clashes (or would the compiler warn of ambiguity?)

Question: is there a convincing argument one way or another?

like image 436
Mawg says reinstate Monica Avatar asked Jan 16 '10 13:01

Mawg says reinstate Monica


People also ask

Do you need using namespace std in C?

using namespace std; are used. It is because computer needs to know the code for the cout, cin functionalities and it needs to know which namespace they are defined.

Can you use namespaces in C?

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

What is the purpose of namespace in C?

Namespaces are used to organize code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries.

Should we use using namespace std in C++?

The statement using namespace std is generally considered bad practice. The alternative to this statement is to specify the namespace to which the identifier belongs using the scope operator(::) each time we declare a type.


2 Answers

Personally I prefer the using declaration rather than the using directive.

For example:

#include<string>
using std::string;

string x="abc";

Using the using directive brings the entire namespace into scope which might cause name collision problems later.

For more information read this(Strongly recommended).

like image 132
Prasoon Saurav Avatar answered Sep 18 '22 00:09

Prasoon Saurav


usings are fine in cpp files. You would prefer the second syntax in headers so you don't get them propagated throughout your project.

like image 38
Steve Avatar answered Sep 22 '22 00:09

Steve