Using Namespace in C++.

If you are already familiar with C++ programming then you must have seen this line "using namespace std" on top of the code after including all required header files. Many beginners consider this as a part of C++ syntax without trying to understand its exact meaning. In this article, we will discuss namespace and why we use it.


What is Namespace in  C++?

A namespace is a declarative region that provides a scope to the identity functions or variables inside it. They are used to organize code into logic groups and prevent name collisions, mainly when the code base includes multiple libraries. 


Let's understand it using one example condition: 

#include<iostream>

int main()
{
    int n = 0;
    std::cout<<"Enter a number: ";
    std::cin>>n;
    std::cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above example code, we have used std::cout and std::cin instead of simply using cout and cin. The prefix std:: indicates that the name cout and cin are defined inside the namespace named std which stands for "standard library".

A using-declaration lets you use a name from a namespace without qualifying the name with a namespace_name::prefix. 
  • syntax: using namespace::name;
C++ Example code:
#include<iostream>
using std::cin;
using std::cout;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5

In the above code example, you will notice that we are using cout and cin without std:: because we have already defined that we are using cin and cout from the std namespace so we don't have to write std:: again, and again.

C++ using namespace std Example.

using namespace std in C++ code indicates that any name that we are going to use in our code belongs to the std (standard library) namespace. It is mainly used for our input/output operations.
#include<iostream>
using namespace std;

int main()
{
    int n = 0;
    cout<<"Enter a number: ";
    cin>>n;
    cout<<"The entered number is: " << n;
    return 0;
}
Output:
Enter a number: 5
The entered number is: 5
 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS