Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What requires me to declare "using namespace std;"?

This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare

using namespace std;

in C++ programs?

like image 939
vette982 Avatar asked Feb 07 '10 20:02

vette982


People also ask

Why do you need using namespace std?

namespace is needed because if a functionalities like cout is used, but not defined in the current scope computer needs to know where to check. so namespace needs to be included. Because we are writing the code outside the std namespace.

What can be declared in a namespace?

A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope.

How do you declare a STD in C++?

Specify the standard namespace, for example: std::printf("example\n"); Use the C++ keyword using to import a name to the global namespace: using namespace std; printf("example\n");

Is it mandatory to use namespace in C++?

It isn't. In fact, I would recommend against it. However, if you do not write using namespace std , then you need to fully qualify the names you use from the standard library. That means std::string instead of string , std::cout instead of cout , and so forth.


2 Answers

Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.

However,

using namespace std;

is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like

using std::string;
like image 119
Péter Török Avatar answered Sep 19 '22 01:09

Péter Török


Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::

like image 41
Colin Valliant Avatar answered Sep 21 '22 01:09

Colin Valliant