Variables used in the main program are by default global variables, and these can be used anywhere in the program, including within any subroutines. Within a subroutine, local variables can be used within the subroutine, and these exist only during the execution of the subroutine. They cannot be accessed outside the subroutine and changing them has no effect on any variable outside the subroutine, even if the variable happens to have the same name as the local variable.
The ability to declare local variables is very useful because it ensures that each subroutine is completely self-contained and independent of any global variables that have been declared in the main program.
The principle of encapsulation of all the variables needed in a subroutine is very important in programming. A subroutine written according to this principle can be tested independently and used many times in many different programs without the programmer needing to know what variables it uses. Any variable in the calling program which coincidentally has the same name as a local variable declared in the subroutine will not cause an unexpected side-effect.
Here is an example of local and global variable. Look though the code and guess what will happen.
#include <iostream>
using namespace std;
int global_variable = 114514;
int* local_variable_func()
{
int local_variable = 919810;
cout << "You can access the global variable within a subroutine" << endl;
cout << "The value of global_variable=" << global_variable << endl;
cout << "The address of global=" << &global_variable << endl;
cout << "You cannot access the local variable outside a subroutine" << endl;
cout << "The value of the local_variable=" << local_variable << endl;
cout << "The addess of the local_variable=" << &local_variable << endl;
return &local_variable;
}
int main()
{
int value = *local_variable_func(); // Don't do this in real life!
cout << "Attempt to access local variable outside the subroutine" << endl;
cout << value << endl;
cout << "But the program will just crash!" << endl;
}
Run this code online: https://onlinegdb.com/BkN3l-A7O
Here is a sample output. Yours run might have a different memory address, but the basic idea is the same.
You can access the global variable within a subroutine
The value of global_variable=114514
The address of global=0x601078
You cannot access the local variable outside a subroutine
The value of the local_variable=919810
The addess of the local_variable=0x7ffcf81ed7dc
Segmentation fault (core dumped)
You can see we can access the global variable from anywhere, but when we want to access the local variable in the local_variable_func, the Segmentation fault error occurs and the program just crash. This is because the local variable is alreadly destroyed after the subroutine finished its task.