Variable scope
- This article is a basic introduction. For a complete, advanced description see this article
In C++ programs, a scope is one of the core concepts. Broadly speaking, a scope is a region of code, where a variable, once declared, can be used. At most one variable with the same name can be declared in a specific scope. The specific variable can not be used outside the scope, unless there is another variable with the same name available.
A scope is opened with the {
character and closed with the }
character. These characters always open and close a scope and thus they must be always properly paired.
Scopes may be nested, that is, a scope may contain other scopes. Each inner scope may use the variables declared in the outer scopes that contain the scope. The reverse is not true: variables declared in the inner scopes may not be used in the outer scopes.
Note, that {
and }
characters within character or string literals (e.g. "abc{bce") do not impact scoping in any way.
The example below demonstrates the basic properties of scopes:
void example() { int x = 2; { int y = 5; // x and y can be used here { int z = 6; // x, y and z can be used here } // x and y can be used here } // only x can be used here }
Name hiding
It's possible to declare a variable with the same name as a variable from the outer scope. The newly created variable will shadow the variable of the outer scope, that is, all uses within the inner scope will refer to the newly created variable. For example:
Output:
2552
Generally, this feature is used rarely because it usually leads to hard to understand code and hard to find bugs.