• In C++ namespace is a logical division of the code which is designed to stop the naming conflict.
  • In C++ namespace defines the scope where the identifiers such as variables, class, functions are declared.
  • The main purpose of using namespace is to remove the ambiguity in C++. If different task occurs with the same name their ambiguity occurs.
  • In different namespaces functions are declared, 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.
  • C++ language consists of a standard namespace which contains inbuilt classes and functions.
  • In our program by using the statement “using namespace std;” includes the namespace “std”.

Syntax

namespace namespace_name  
{
//body of namespace;
}

Syntax of accessing the namespace variable

namespace_name::member_name; 

Sample code

 using namespace std;  
namespace addition
{
int a=5;
int b=5;
int add()
{
return(a+b);
}
}

int main() {
int result;
result=addition::add();
cout<<result;
return 0;
}

Output

 

Categorized in: