Variable Scope:

There are three places in C++ programming language where the variables are initialized and declared.

  1. Inside a function
  2. Outside a function
  3. As function parameters (it will be discussed on later chapter)

Local variables

A variable declared inside a function is known as local variable.

Scope of local variables

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.

Lifetime of local variables

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.

Global Variables

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.

Scope of global variables

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.

Lifetime of global variables

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.