logo codesdope

What is a namespace?(C++)

   Saikat


Answers

  •    Aakhya Singh

    Namespaces are regions which are used to provide scope for identifiers (variables, classes, functions, etc). Any identifier declared within a namespace cannot be directly accessed outside that namespace.

    Let’s see an example.

    Suppose we have a namespace named num. We declared a variable named a inside this namespace and assigned it a value 2.

    Syntax to declare the namespace num

    namespace num
    

    Now, to access the variable outside the namespace num, we have to use the operator :: as shown below.

    num::a
    

    Here is the whole code.

    #include <iostream>
    
    namespace num { 
    	int a = 2;
    }
    
    int main(void) {
    	std::cout << num::a << std::endl;
    	return 0;
    }
    

    We can also use the keyword using to introduce the variable a outside the scope of the namespace num.

    #include <iostream>
    
    namespace num { 
    	int a = 2;
    }
    
    int main(void) {
    	using num::a;
    	std::cout << a << std::endl;
    	return 0;
    }
    

    Alternatively, we can introduce the whole namespace num using the using keyword.

    #include <iostream>
     
    namespace num { 
    	int a = 2;
    }
     
    int main(void) {
    	using namespace num;
    	std::cout << a << std::endl;
    	return 0;
    }
    

    Similarly, cout and endl are defined in the std namespace.



Write your answer
Close

Welcome.please sign up.

Close

Welcome.please login.