Storage Classes in C++
Storage classes are used to specify the lifetime and scope of variables. How storage is allocated for variables and How variable is treated by complier depends on these storage classes.
These are basically divided into 5 different types:
- Global variables
- Local variables
- Register variables
- Static variables
- Extern variables
These are defined at the starting , before all function bodies and are available throughout the program.
using namespace std;
int globe; // Global variable
They are defined and are available within a particular scope. They are also called Automatic variable because they come into being when scope is entered and automatically go away when the scope ends.
The keyword auto is used, but by default all local variables are auto, so we don't have to explicitly add keyword auto before variable dedaration. Default value of such variable is garbage.
This is also a type of local variable. This keyword is used to tell the compiler to make access to this variable as fast as possible. Variables are stored in registers to increase the access speed.
But you can never use or compute address of register variable and also , a register variable can be declared only within a block, that means, you cannot have global or static register variables.
Static variables are the variables which are initialized & allocated storage only once at the beginning of program execution, no matter how many times they are used and called in the program. A static variable retains its value until the end of program.
static int i = 10;
cout << i;
fun(); // Output = 11
fun(); // Output = 12
fun(); // Output = 13
i is static, hence it will retain its value through function calls, and is initialized only once at the beginning.
Static specifiers are also used in classes, but that we will learn later.
This keyword is used to access variable in a file which is declared & defined in some other file, that is the existence of a global variable in one file is declared using extern keyword in another file.