/    /  CPP – Storage Classes In C++

Storage Classes in C++

Storage classes serve to specify the lifetime and scope of variables. How storage is allocated for variables and how a variable is treated by the compiler 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 start, before all function bodies, and are available throughout the program.

 

Local variables: They are defined and available within a specific scope. They are also called Automatic variables because they are created when the scope is entered and disappear automatically when the scope is completed. The auto keyword is used, but by default all local variables are auto, so we don’t need to explicitly add the auto keyword prior to declaring the variable. This variable defaults to garbage.

 

Register variables: It is also a kind of local variable. This keyword is used to tell the compiler to access this variable in as short a time as possible. Variables are saved in registers to increase the speed of accessBut you may never use or calculate the address of the register variable and also a register variable may be declared only in a block, which means that you cannot have global or static register variables.

 

Static Variables: Static variables are those variables which are initialized and assigned to storage only once at the beginning of the program run,

 no matter how often they are utilized and called into the program. A static variable retains its value until the end of the program.

Since i is static, it will retain its value by means of function calls and will be initialized only once at the beginning.

 

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