Storage Classes in C++ Programming Language
In the C++ programming language, there are variables and each variable has a data type. When we declared the variable, the compiler assigned the storage class by default and that storage class is used to define the lifetime and visibility of a variable or function within the program.
Lifetime refers to the period during which the variable remains active whereas visibility refers to the module of a program during which the variable is accessible.
We used five types of storage in C++ program, which are as follows -
- Automatic
- Register
- Static
- External
- Mutable
Automatic Storage Class
All local variables have a default storage class which is an automatic storage class. The automatic storage class has a pre defined keyword that is auto. The auto keyword is automatically applied to all local variables.
The above example defines two variables with the same storage class, auto can only be used within functions.Register Storage Class
Register storage class is employed to declare register variables. Register variable is similar to auto variable. It allocates memory in registers as compared to RAM. It's size is same as the size of register. This makes operations on register variables much faster than other variables stored in memory during runtime. The point to note is that we will not get the address of the register variable.
Static Storage Class
Static variables are initialized only once and exist until the end of the program. It retains it's value between multiple function calls.
The default value of a static variable is 0 which is provided by the compiler.
Output -
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
External Storage Class
The extern variable is visible to all programs. It is used when two or more files are sharing the same variable or function.