Define namespace in C++.

  • The namespace is a logical division of the code which is designed to stop the naming conflict.
  • The namespace defines the scope where the identifiers such as variables, class, functions are declared.
  • The main purpose of using namespace in C++ is to remove the ambiguity. Ambiquity occurs when the different task occurs with the same name.
  • For example: if there are two functions exist with the same name such as add(). In order to prevent this ambiguity, the namespace is used. Functions are declared in different namespaces.
  • C++ consists of a standard namespace, i.e., std which contains inbuilt classes and functions. So, by using the statement “using namespace std;” includes the namespace “std” in our program.
  • Syntax of namespace:

  1. namespace namespace_name  
  2. {  
  3.  //body of namespace;  
  4. }  

Syntax of accessing the namespace variable:

  1. namespace_name::member_name;  

Let’s understand this through an example:

  1. #include <iostream>  
  2. using namespace std;  
  3. namespace addition  
  4. {  
  5.     int a=5;  
  6.     int b=5;  
  7.     int add()  
  8.     {  
  9.         return(a+b);  
  10.     }  
  11. }  
  12.   
  13. int main() {  
  14. int result;  
  15. result=addition::add();  
  16. cout<<result;  
  17. return 0;  
  18. }  

Output:

10