C++ Programming
Variables also reside in a specific scope. The scope of a variable is the most important factor to determines the life-time of a variable. Entrance into a scope begins the life of a variable and leaving scope ends the life of a variable. A variable is visible when in scope unless it is hidden by a variable with the same name inside an enclosed scope. A variable can be in global scope, namespace
scope, file scope or compound statement scope.
As an example, in the following fragment of code, the variable 'i' is in scope only in the lines between the appropriate comments:
{
int i; /*'i' is now in scope */
i = 5;
i = i + 1;
cout << i;
}/* 'i' is now no longer in scope */
There are specific keywords that extend the life-time of a variable, and compound statement define their own local scope.
// Example of a compound statement defining a local scope
{
{
int i = 10; //inside a statement block
}
i = 2; //error, variable does not exist outside of the above compound statement
}
It is an error to declare the same variable twice within the same level of scope.
The only scope that can be defined for a global variable is a namespace
, this deals with the visibility of variable not its validity, being the main purpose to avoid name collisions.
The concept of scope in relation to variables becomes extremely important when we get to classes, as the constructors are called when entering scope and the destructors are called when leaving scope.