There are three places in C++ programming language where the variables are initialized and declared.
- Inside a function
- Outside a function
- As function parameters (it will be discussed on later chapter)
A variable declared inside a function is known as local variable.
The area where a variable can be accessed is called the scope of variable. Local variable can only be used inside a function where it is declared.
The time period for which the variable exists in the memory is known as life time of that variable.
The lifetime of a local variable starts when the control enters the function in which the variable is declared. Local variable is automatically destroyed when the control exits from the function. And its value is also lost when it is destroyed.
A variable declared outside a function is global variable. Global variables can be used by all the functions of a program. Their values are shared among different functions.
Global variables can be used by all functions in the program. It means that these variables are globally accessed from any part of the program. Normally global variables are declared before main function.
Global variables exist in the memory as long as the program is running. These variables are destroyed from the memory when the program terminates. These variables occupy memory larger than local variables.