Scope

就是阿个

The scope of a variable: the part of the program in which the variable can be accessed

A variable cannot be used before it is defined

Scope: Region of code

  • “In Scope”

    • Name declared in a scope is valid until the end of the scope.

  • “Out of Scope”

    • Variable is inaccessible outside the region of code within which is it defined.

Types of Scope

  • Global scope: the area of code outside of any other scope

    • Avoid for variables

    • OK for constants

  • Namespace scope: named scope nested in the global scope or in another namespace

  • Class scope: area of code within a class

  • Local scope: between {…} braces of a block or in a function argument list

    • Can be nested

  • Statement Scope: In a for-statement

#include <iostream>
// global scope
int x = 1;
namespace ns {
    // namespace scope
    int x = 2;
}
void foo() {
    // local (function) scope
    int x = 3;
    {
        // local (block) scope
        int x = 4;
        {
            // local (nested-block) scope
            int x = 5;
            for (int x=6; x<7; x++) {
                // statement scope
                std::cout << x << std::endl;
            }
            std::cout << x << std::endl;
        }
        std::cout << x << std::endl;
    }
    std::cout << x << std::endl;
}
int main() {
    foo();
    std::cout << ns::x << std::endl;
    std::cout << x << std::endl;
    return 0;
}

Last updated

Was this helpful?