Tech

Unary Scope Resolution Operator–Functions–STRUCTURED PROGRAMMING Course Notes

Unary Scope Resolution Operator

  • C++ provides the unary scope resolution operator ( :: ) to access a global variable when a local variable of the same name is in scope.
  • This makes it possible to declare local & global variables of the same name.
  • The unary scope resolution operator cannot be used to access a local variable of the same name in an outer block.
  • A global variable can be accessed directly without the unary scope resolution operator if the name of the global variable is NOT the same as that of a local variable in scope.
  • Tip: Always using the unary scope resolution operator ( :: ) to refer to global variables. This will help with 3 things:
    1. makes programs easier to read & understand (because it makes it clear that we are intending to access a global variable);
    2. makes programs easier to modify, by reducing the risk of name collisions with nonglobal variables;
    3. eliminates logic errors that might occur if a non-global variable hides the global variable.
    4. In short, always use the unary scope resolution operator( :: ).
  • Tip: Avoid using variables of the same name for different purposes in a program. Although allowable, this can lead to errors.