Storage Classes in C++

Written by

Vaaruni Agarwal

Storage Classes

A Storage Class is used to define the scope and lifetime of the variables or functions in C++. 

They are of utmost importance as by using these Storage Classes one can change the visibility, scope, storage location and the lifetime of the variables as per the need of the program. 

There are five storage classes in C++, these are as follows.

  • auto 
  • register 
  • static 
  • extern 
  • mutable 

 

To assign a storage class, the Syntax is:

storage class data type variable_name/ function_name

 

The auto Storage Class :

The auto storage class is the default storage class for all the local variables

int mount; 

auto int month; 

}

The example above defines two variables with the same storage class, auto. Auto can only be used within functions for the local variables. 

 

The register Storage Class :

The register storage class is used to define local variables that should be stored in a register instead of RAM to ensure faster access of such variables, generally counter variables are assigned a register class, as they need to be accessed frequently and their values change often.

register int i; 

}

 

The static Storage Class :

The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program.

Thus static local variables have their lifetime throughout the program but their scope is limited to that function in which they are declared and their values are also preserved during the whole program.

 

The extern Storage Class :

The extern storage class is used to give a reference to a global variable that is visible to ALL the program files. 

 

The mutable Storage Class :

The mutable storage class applies only to class objects, which will be discussed later in detail. It allows a member of an object to override const member function. That is, a mutable member can be modified by a const member function.

Storage Classes in C++