Local and global variables
It is often necessary to use additional variables that will only be used in the subroutine. Such variables are called
local (or local) and can only be manipulated within the subroutine in which they are created.
Local variable scope is the curly bracketed block within which it is declared
The main program in C++ is also a subroutine, so all variables declared inside
main()
are local variables.
Other subroutines don't "know" anything about the local variables of other subroutines.
Thus, it is possible to limit the scope (scope) of a variable only to the subroutine where it is really needed. In programming, this technique is called
encapsulation - hiding a variable from being changed from outside.
If it is necessary to declare a variable that would be visible anywhere in the program (in any subroutine), then such variables are declared outside of all subroutines (see program 3 from the table below).
Such variables are called
global.
In C++, when the program starts, all global variables are automatically set to zero (boolean variables take the value false
).
Analyze three programs:
1) In this program, the variable i is local. A local variable is declared inside a subroutine |
2) Here, even if there is a variable i in the main program (with value 7), a new local variable i with value 5 will be created.
When you run this program, the screen will display the value 75 |
3) This program has a global variable i. Its value can be changed inside a subroutine, and inside the main program
The procedure will work with the global variable i and it will be assigned a new value equal to 2. The value 2 | is displayed on the screen
void test()
{
int i = 5;
cout << i;
}
|
void test()
{
int i = 5;
cout << i;
}
main()
{
int i = 7;
cout << i;
test();
}
|
#include <iostream>
using namespace std;
int i;
void test()
{
i = 2;
}
main()
{
test();
cout << i;
}
|