Skip to content

Scopes

Scopes

The context in which a name is visible is called its scope. For example, if you declare a variable x within a function, x is only visible within that function body. It has local scope.

1
2
3
4
5
6
7
8
9
int x = 1;
std::cout << "External x: " << x << '\n';
for (int i = 0; i < 2; ++i) {
    int y = 2;
    std::cout << "Internal i: " << i << '\n';
    std::cout << "External x: " << x << '\n';
    std::cout << "Internal y: " << y << '\n';
}
std::cout << "External x: " << x << '\n';

1
2
3
// This won't work:
// std::cout << "Internal i: " << i << '\n';
// std::cout << "Internal y: " << y << '\n';

Share Snippets