![]() |
VOOZH | about |
In this article, we will discuss the use of "using namespace std" in the C++ program.
As the same name can't be given to multiple variables, functions, classes, etc. in the same scope. So, to overcome this situation, namespace is introduced.
Example
Below is the C++ program illustrating the use of namespace with the same name of function and variables:
2 This is fun() of n1 5 This is fun() of n2
Explanation:
Every time we use the identifiers defined inside a namespace in another scope, we need to use the scope resolution operator (::) in a variable or a function. But we can avoid it by utilizing the "using" directive.
The using directive makes the declarations and definitions of the given namespace visible in the current scope.
Example
Below is the C++ program demonstrating the use of the "using" directive:
2 This is fun() of n1
Explanation:
Also, "using" only makes the namespace visible in the scope where it is used. For Example, if "using namespace n1" is written inside the main() and we try to use the members (fun() and x in this case) in the different functions, it would give a compile-time error.
Note: The compiler will only look up in the given namespace only if the identifier is not found in the current scope.
It is known that "std" (abbreviation for the standard) is a namespace where all the C++ Standard Library Functions, Classes and other stuff is declared. So, the members of the "std" namespace are cout, cin, endl, etc.
So, to avoid the usage of scope resolution operator with std namespace for every standard library component, we use the statement "using namespace std" to make the compiler look for the given identifier in the std namespace.
If we don't use the "using namespace std" statement in our code, our code will look like this"
The value of x is 10
Explanation: The output of the program will be the same whether write "using namespace std" or use the scope resolution.
Note: It is recommended to not use the "using namespace std" in your development projects as you may use the different identifiers declared inside different namespaces and the before statement will make the std namespace visible in all of the global scope.