C++ Storage Class

Storage class associated with variables that provides information about the location and visibility of variables. The storage class specifies the part of a program within which the variables can be recognized. There are the following types of storage class in C++ language.

  • auto
  • static
  • extern
  • register
  • mutable


auto Storage Class

The auto is the default storage class for all the local variables. Local variable is known only to the function in which it is declared.

Syntax

  1. auto int num;


static Storage Class

The static storage class preserves the value of a variable even after the control is transferred to the calling function. Using static as a local variable allows to maintain their values between the function in which it is defined and using static as a global variable can be accessed in any part of the program.

Syntax

  1. int num;
  2. static int num;


extern Storage Class

It is a global variable. It is known to all function in the file. It is used to give a reference of a global variable. The extern variable can not be initialized. Simply it can be said that extern is used to declare the global variable or function in another program. When more than one file share the same global variable or function you have to use the extern keyword.

Syntax

  1. extern void my_func();


register Storage Class

The register is used to specify local variables which needs to be stored in the register instead of RAM. When you need the maximum size variable equal to the register size you should use the register storage class. It works faster than the variable placed in RAM.

Syntax

  1. register int num;


mutable Storage Class

Sometime you need to modify one or multiple data items of a class using const function. It can be easily done by the mutable storage class. It allows a particular member of the data of const object to be modified. It means if a data member of a class is declared as mutable storage class it can be modified by the object which is declared as const. It will be discussed broadly later on this tutorial.

Syntax

  1. mutable int num;