I have viewed some source that contained an identifier with a scope operator preceding it.
Ex:

::var

What does that mean/do?

Dani AI

Generated

Brief clarification that builds on and : the :: token is the C++ scope-resolution operator used to qualify names. A leading ::name specifically requests the name from the global (namespace) scope; it does not reach into an inner block or "the next outer local scope." Use it when a local name shadows a namespace/global name or when you must disambiguate between similarly named namespaces.

A common use that isn't shown above is disambiguating between a local namespace and a global one. For example:

namespace lib { void f(); }

namespace app {
  namespace lib { void f(); }

  void g() {
    lib::f();    // calls app::lib::f
    ::lib::f();  // calls global lib::f
  }
}

Be aware of two practical gotchas:

  • :: only affects compile-time name lookup. It cannot be used to access an automatic (block) variable declared in an enclosing block; only namespace-/global-scope names can be selected with a leading :: (as hinted).
  • Qualifying a call (for example ns::foo(...) or ::foo(...)) can suppress argument-dependent lookup (ADL) and thus change overload resolution. That matters when free functions rely on ADL to be found.

For precise language rules and examples, see the C++ reference on the scope-resolution operator and on argument-dependent lookup:

Recommended Answers

All 2 Replies

This is C++'s scope resolution operator. This resets the scope of that variable in this case. You see this all the time when you declare a class and then implement its functions elsewhere.

For example, you have

class myClass {
int myFunction();
};

int myClass::myFunction()
{
 ...
}

The :: is giving access to the function in myClass outside of this scope.

Now for another example, using var

int var = 3;

int main()
{
    float var = 4.5;
    {
          double var = 6.5;
          int myVar = ::var;
    }
}

Here, using the scope resolution operator, myVar is going to be set to 3.

Hope this helps

::name is explicitly specifying that name is in global namespace

example 1:

int i = 3;
int main()
{
   int i = 4;
   if(true)
   {
       int i = 5;
       int j = ::i; //j is set to 3
   }  
}

example 2:

int main()
{
   int i = 4;
   if(true)
   {
       int i = 5;
       int j = ::i; //ERROR there is no i in the global namespace. If you wanna access the i just outside the block, that is, the one with value 4, well, you can't :)  
   }  
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.