Storage classes:

Where the variables are declared in C++ program, is determined by storage classes. The scope and life time of variables is defined by storage variables. It is very clear from the name storage classes that it specifies how variables are stored in the memory.


Local variables

These variables are declared inside any module in a C++ program.

Scope of local variables

Local variable can only be used inside a function where it is declared. Scope of variable is the area in which variables can be used.

Lifetime of local variables

Local variable is automatically destroyed (values also) after executing the function inside which they were declared.


Global Variables

A variable declared outside a program module is global variable. All functions in the program can access these variables. Their values are shared among different functions.

Scope of global variables

Global variables can be used by all functions in the program. Normally they are always declared after the header files.

Lifetime of global variables

Their life is equal to as long as the program is running.

These two types of variables have been discussed earlier.


Static variables

Static variables are initialized once at the beginning of the program. The value of static variable remains constant. They are sometimes used to count objects referring to object oriented programming (it will be discussed later.

Scope of static variables

Just like global variables, static variable can also be used by all functions of a program.

Lifetime of static variable

The lifetime of static variables is equal to the lifetime of the program in which they are used.


Auto variable

Local variables are also called automatic variables. Automatic variables have the same scope and lifetime as the local variables.

When a variable is declared locally, by default it is declared as an auto variable.


Register variable

When a variable is created it is automatically stored in RAM. To store a variable in a register, register variable is used. These variables are accessed fast by the compiler.

Scope of register variable

Register variable is a type of local variable it means it can only be used inside a function where it is declared.

Lifetime of register variable

Register variable destroys when the control exits from the function where it was declared.