Open In App

Why it is important to write “using namespace std” in C++ program?

In this article, we will discuss the use of “using namespace std” in the C++ program.

Need of namespace:



Program 1:

Below is the C++ program illustrating the use of namespace with the same name of function and variables:






// C++ program to illustrate the use
// of namespace with same name of
// function and variables
#include <iostream>
using namespace std;
 
// Namespace n1
namespace n1 {
int x = 2;
 
// Function to display the message
// for namespace n1
void fun()
{
    cout << "This is fun() of n1"
         << endl;
}
}
 
// Namespace n2
namespace n2 {
 
int x = 5;
 
// Function to display the message
// for namespace n2
void fun()
{
    cout << "This is fun() of n2"
         << endl;
}
}
 
// Driver Code
int main()
{
    // The methods and variables called
    // using scope resolution(::)
    cout << n1::x << endl;
 
    // Function call
    n1::fun();
 
    cout << n2::x << endl;
 
    // Function call;
    n2::fun();
 
    return 0;
}

Output: 
2
This is fun() of n1
5
This is fun() of n2

 

Explanation:

Program 2:

Below is the C++ program demonstrating the use of the “using” directive:




// C++ program to demonstrate the use
// of "using" directive
#include <iostream>
using namespace std;
 
// Namespace n1
namespace n1 {
int x = 2;
void fun()
{
    cout << "This is fun() of n1"
         << endl;
}
}
 
// Namespace is included
using namespace n1;
 
// Driver Code
int main()
{
    cout << x << endl;
 
    // Function Call
    fun();
 
    return 0;
}

Output: 
2
This is fun() of n1

 

Explanation:

If “using namespace n1” is written inside the main() and tries to use the members (fun() and x in this case) in the different functions it would give a compile-time error.

Program 3:

Below is the C++ program illustrating the use of “using namespace” inside main() function:




// C++ program illustrating the use
// of "using namespace" inside main()
 
#include <iostream>
using namespace std;
 
// Namespace n1
namespace n1 {
int x = 2;
void fun()
{
    cout << "This is fun() of n1"
         << endl;
}
}
 
// Function calling function
void print()
{
    // Gives error, used without ::
    fun();
}
 
// Driver Code
int main()
{
    // Namespace inside main
    using namespace n1;
 
    cout << x << endl;
 
    // Function Call
    fun();
 
    return 0;
}

Output:

Explanation:
 

 




// Code written in the iostream.h file
 
namespace std {
ostream cout;
i0stream cin;
// and some more code
}

Explanation:

Program 4:

Below is the C++ program illustrating the use of std:




// C++ program to illustrate
// the use of std
#include <iostream>
 
// Driver Code
int main()
{
    int x = 10;
    std::cout << " The value of x is "
              << x << std::endl;
    return 0;
}

Output: 
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.


Article Tags :