Namespaces
Variants
Actions

Variable scope

From cppreference.com
Revision as of 04:57, 22 December 2013 by P12 (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)


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 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
}