Scopes are often bundled with variables, limiting the scope of the variables available, and also defining the life cycle of variables: when and when to destroy them. Scopes are generally divided into: global scope and local scope.
Global scope (global variables)
Variables defined outside the body of the function being used are global variables and have global scope. It is created before the main function executes, and is destroyed after the Mian function finishes. The following code shows the creation and destruction of global variables:
1:
2: {
3: Public :
4: World ()
5: {
6: "Hello world.\n";
7: }
8:
9: ~world ()
Ten: {
One: "goodbye.\n";
: }
: };
:
: World TheWorld;
:
+: int main ()
: {
: "Hello from main.\n";
: return 0;
: }
The result of this code execution is:
The TheWorld object is created before the main function executes, and is destroyed after main ends.
Local scope (local variable)
A local scope is an area surrounded by a pair of curly braces that is created when the program flow enters its scope and is destroyed when it exits the scope. The following code demonstrates the creation and destruction of local variables:
1:
2: {
3: Public :
4: World (int id)
5: : identifier (ID)
6: {
7: ". \ n";
8: }
9:
Ten: World ()
All: : identifier (0)
: {
: "Hello from default constructor. \ n";
: }
: ~world ()
: {
: ". \ n";
: }
:
: Private:
: int identifier;
: };
At:
: World TheWorld;
:
+: int main ()
: {
: World Smallworld (1);
£ º
: For (int i = 2; i < 4; i + +)
: {
: World Aworld (i);
: }
:
: World Onemoreworld (4);
: }
The result of the execution is:
Description
- Added a constant member identifier for world class world to identify different instances of world. Identifier is initialized in the preamble of the constructor.
- When executed, call the default constructor before main to create the TheWorld
- Enter the main function, first create smallworld (identifier = 1), Smallworld is the local variable within the main function, the scope is the entire main function
- Enter a for loop local scope to create and destroy world two instances of identifier = 2 and identifier = 3
- For scope end, go to main local scope, create local variable onemoreworld (identifier = 4)
- The main scope ends and the local variables within the main scope are destroyed. The local variables are destroyed in the opposite order that they were created, destroying Onemoreworld first and then Smallworld
- The last program executes to the end, destroying the global variable theworld.
C + + Scopes