411 REFERENCE · Wikibooks
C++ Programming/Programming Languages/C++/Code/Statements/Scope
Reference material by Wikibooks contributors. This retains its source identity and is not 411 news reporting.
Scope
In any language, scope (the context; what is the background) has a high impact on a given action or statement validity. The same is true in a programming language.
In a program we may have various constructs, may they be objects, variables or any other such. They come into existence from the point where you declare them (before they are declared they are unknown) and then, at some point, they are destroyed (as we will see there are many reasons to be so) and all are destroyed when your program terminates.
We will see that variables have a finite life-time when your program executes, that the scope of an object or variable is simply that part of a program in which the variable name exists or is visible to the compiler.
Global scope
The default scope is defined as global scope, this is commonly used to define and use global variables or other global constructs (classes, structure, functions, etc...), this makes them valid and visible to the compiler at all times.
It is considered a good practice, if possible and as a way to reduce complexity and name collisions, to use a namespace scope for hiding the otherwise global elements, without removing their validity.
Local scope
A local scope relates to the scope created inside a compound statement.
The only exceptional case is the for keyword. In that case the variables declared on the for initialization section will be part of the local scope.
C++ Programming