top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is global namespace in c++?

+1 vote
341 views
What is global namespace in c++?
posted Jun 28, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+2 votes
 
Best answer

In C++, every name has its scope outside which it doesn't exist. A scope can be defined by many ways : it can be defined by namespace, functions, classes and just { }.So a namespace, global or otherwise, defines a scope. The global namespace refers to using ::, and the symbols defined in this namespace are said to have global scope. A symbol, by default, exists in a global namespace, unless it is defined inside a block starts with keyword namespace, or it is a member of a class, or a local variable of a function.

int definedInGlobalNamespace; //this a is defined in global namespace
       //which means, its scope is global. It exists everywhere.
namespace N
{
     int nonGlobalNamespace;  //it is defined in a non-global namespace called `N`
             //outside N it doesn't exist.
}

and inside namespace N hides the name varDefined in the global namspace.the name in the function and class hides the name in the global namespace. If you face such situation, then you can use ::varDefined to refer to the name defined in the global namespace:

int varDefined = 10;

namespace N
{
    int varDefined = 100;

    void f()
    {
         int varDefined = 1000;
         std::cout << varDefined << std::endl;      //prints 1000
         std::cout << N::varDefined << std::endl;   //prints 100 
         std::cout << ::varDefined << std::endl;    //prints 10
    }
}
answer Jun 28, 2016 by Shivam Kumar Pandey
...