Open In App

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

Last Updated : 02 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Need of namespace:

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

Program 1:

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

C++




// 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:

  • In the above example program, both n1 and n2 have a variable and function of the same name x and fun() respectively.
  • The namespace is used to decrease or limit the scope of any variable or function.
  • As in the above code variable x and method fun() were limited to namespaces n1 and n2. Thus, their scope was not outside the n1 or n2.
  • Every time using the scope resolution operator (::) in a variable or a function defined is not required, it can be solved with “using” directive.
  • The using directive means to include the whole code written in the namespace in the closing scope.

Program 2:

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

C++




// 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:

  • In the above program, after writing “using namespace n1“, there is no need to use the scope resolution for utilizing the members of n1.
  • It can be interpreted as “using” copies of the code written in the namespace to the scope in which it has been written.

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++




// 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:
 

  • 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.
  • Below is the code snippet in C++ showing content written inside iostream.h:

 

C++




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


Explanation:

  • Now when cout<<“GeeksforGeeks”; is written, the compiler searches for cout in our program which is kept in the std namespace, so the instruction given to the compiler that if the compiler doesn’t find anything in the current scope, try finding it in the std namespace.
  • It is not necessary to write namespaced, simply use scope resolution (::) every time uses the members of std. For example, std::cout, std::cin, std::endl etc.

Program 4:

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

C++




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



Similar Reads

std::fixed, std::scientific, std::hexfloat, std::defaultfloat in C++
Formatting in the standard C++ libraries is done through the use of manipulators, special variables or objects that are placed on the output stream. There are two types of floating point manipulators namely, fixed floating point and scientific floating point. These all are defined in header &lt;iostream&gt;. Use of precision : In the default floati
3 min read
Why "using namespace std" is considered bad practice
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. Although the statement saves us from typing std:: whenever we wish to access a class or type defined in the std namespace, it
5 min read
std::oct , std::dec and std::hex in C++
This function is used to set the base to octal, decimal or hexadecimal. It sets the basefield format flag for the str stream to the specified base std::oct : When basefield is set to octal, integer values inserted into the stream are expressed in octal base (i.e., radix 8). For input streams, extracted values are also expected to be expressed in oc
2 min read
std::string::length, std::string::capacity, std::string::size in C++ STL
Prerequisite: String in C++ String class is one of the features provided by the Standard template library to us, So it comes up with great functionality associated with it. With these Functionalities, we can perform many tasks easily. Let's see a few of the functionalities string class provides. Header File &lt;string&gt; String Functionalities The
6 min read
std::stod, std::stof, std::stold in C++
std::stod() : It convert string into double. Syntax: double stod( const std::string&amp; str, std::size_t* pos = 0 ); double stod( const std::wstring&amp; str, std::size_t* pos = 0 ); Return Value: return a value of type double Parameters str : the string to convert pos : address of an integer to store the number of characters processed. This param
3 min read
std::setbase, std::setw , std::setfill in C++
The useful input/output manipulators are std::setbase, std::setw and std::setfill. These are defined in and are quite useful functions. std::base : Set basefield flag; Sets the base-field to one of its possible values: dec, hex or oct according to argument base.Syntax : std::setbase (int base);decimal : if base is 10hexadecimal : if base is 16octal
3 min read
How to Run a C++ Program Without Namespace?
Prerequisite: Namespace in C++ If we want to run a program without using a namespace, we have to the std keyword along with the space resolution operator (::) in every printing line and variable declaration, For example, std::cout&lt;&lt;"geeksforgeeks"; Example: C/C++ Code // C++ Program without the use of using namespace std; #include &lt;iostrea
1 min read
std::tuple, std::pair | Returning multiple values from a function using Tuple and Pair in C++
There can be some instances where you need to return multiple values (maybe of different data types ) while solving a problem. One method to do the same is by using pointers, structures or global variables, already discussed here There is another interesting method to do the same without using the above methods,  using tuples (for returning multipl
2 min read
Cons of using the whole namespace in C++
A namespace is a declarative region that provides a scope to the identifiers (the names of types, functions, variables, etc) inside it. Namespaces are used to organise code into logical groups and to prevent name collisions that can occur especially when your code base includes multiple libraries. Please refer need of namespace in C++ for details.
2 min read
Difference between std::set vs std::vector in C++ STL
Vectors: Vectors are containers similar to dynamic arrays, with the ability to resize when a new element is inserted or deleted from it. It is a template of Standard Template Library or STL, which provides more flexibility to the program. Elements of vectors are placed in contiguous storage and are traversed using iterators. Examples: vector &lt;in
3 min read
Article Tags :
Practice Tags :