Loading

C++: Global and Local Scope

Global and Local Scope

This discussion covers the subject of the scope of a variable. The scope of a variable is the portion of code where we can access the variable. In order to discuss a variable's scope, we introduce the concept of a block. A block is any portion of code delimited by a pair of matching left/right parentheses:

The scope of a variable within a block extends from the variable declaration to the end of the block.

In addition to "if," "while," and other methods of creating blocks like "main," we can create blocks that are not associated with anything. These blocks can be used to impose additional constraints on the scope of variables.

Two variables cannot be declared in the same block with the same name. However, we can have two or more variables declared with the same name in two different blocks, even if one is nested in the other. In this case, the more local variable hides the other variables.

We can declare variables outside of any block. These are called global variables and can be accessed from any code that comes after the declaration.

If a local variable hides a global variable, we can access the global variable using the scope resolution operator.