Storage Classes in C++

Storage classes are used to specify the lifetime and scope of variables. How storage is allocated for variables and How variable is treated by complier depends on these storage classes.

These are basically divided into 5 different types :

  1. Global variables
  2. Local variables
  3. Register variables
  4. Static variables
  5. Extern variables

Global Variables

These are defined at the starting , before all function bodies and are available throughout the program.


using namespace std;
int globe;      // Global variable
void func();
int main()
{
 .....
}

Local variables

They are defined and are available within a particular scope. They are also called Automatic variable because they come into being when scope is entered and automatically go away when the scope ends.

The keyword auto is used, but by default all local variables are auto, so we don't have to explicitly add keyword auto before variable dedaration. Default value of such variable is garbage.


Register variables

This is also a type of local variable. This keyword is used to tell the compiler to make access to this variable as fast as possible. Variables are stored in registers to increase the access speed.

But you can never use or compute address of register variable and also , a register variable can be declared only within a block, that means, you cannot have global or static register variables.


Static Variables

Static variables are the variables which are initialized & allocated storage only once at the beginning of program execution, no matter how many times they are used and called in the program. A static variable retains its value until the end of program.


void fun()
{
 static int i = 10;
 i++;
 cout << i;
}
int main()
{
 fun();      // Output = 11
 fun();      // Output = 12
 fun();      // Output = 13
}

As, i is static, hence it will retain its value through function calls, and is initialized only once at the beginning.

Static specifiers are also used in classes, but that we will learn later.


Extern Variables

This keyword is used to access variable in a file which is declared & defined in some other file, that is the existence of a global variable in one file is declared using extern keyword in another file.

extern keyword in C++