Storage classes are used to define the lifetime and visibility of variables and/or functions in a C++ program.
The lifetime refers to the duration during which a variable remains active, and visibility refers to the modules in the program that can access the variable.
In C++ programs, there are five types of storage classes that can be used:
-
Automatic
-
Register
-
Static
-
External
-
Mutable
Storage Class | Keyword | Lifetime | Visibility | Initial Value |
---|---|---|---|---|
Automatic | auto function block | Local | Local | Garbage |
Register | register function block | Local | Local | Garbage |
Mutable | mutable class | Local | Local | Garbage |
External | extern whole program | Global | Global | 0 |
Static | static whole program | Local | Local | 0 |
👇Click to receive👇
👉Collection of C Language Knowledge Materials
Automatic Storage Class
This is the default storage class for all local variables. The auto keyword is automatically applied to all local variables.
{ auto int y; float y = 3.45;}
The example above defines two variables with the same storage class; auto can only be used inside functions.
Register Storage Class
Register variables allocate memory in the register rather than in RAM.
Its size is the same as the register size. It has faster access speed than other variables. It is recommended to use register variables only for quick access, such as counters.
Note: We cannot obtain the address of a register variable.
register int counter=0;register int counter=0;
Static Storage Class
Static variables are initialized only once and exist before the end of the program. They retain their value between multiple function calls.
The default value of a static variable is 0, provided by the compiler.
#include <iostream>
using namespace std;
void func() {
static int i=0; // Static variable
int j=0; // Local variable
i++;
j++;
cout<<"i=" << i << " and j=" <<j<<endl;
}
int main(){
func();
func();
func();
}
Output:
i= 1 and j= 1
i= 2 and j= 1
i= 3 and j= 1
External Storage Class
External variables are visible to all programs. External variables are used when two or more files share the same variable or function.
extern int counter=0;
Recommended Popular
-
C Language Tutorial – Common Interview Questions Answered (4)
-
CLion Tutorial – Opening Files from Command Line in CLion
-
C++ Tutorial – Detailed Explanation of C++ Recursion