“A storage class defines a variable’s lifetime, default initial value, and scope.”
The variable’s accessibility in these contexts is referred to as scope. Both the initial default value and the lifetime of a variable relate to the value that was there by default before the variable was initialised.
Let’s move on to its types now that we are familiar with the fundamental idea of storage classes. Depending on the kind of variables they hold, there are four different sorts of storage classes. The various storage classes are as follows. Their names give away the stored variables:
- Automatic Variables
- External Variables
- Static Variables
- Register Variables
Auto Storage Class:
This category applies automatically to variables that are created as part of a function but whose storage class has not yet been defined. As it can only be accessed within the function it is initialised in, its scope is minimal. Nothing else can access it. The variable initially holds a trash value until a value is assigned to it. Their lifespan is the amount of time till the function block ends, hence it depends on the duration of the function block.
int a;
auto int a;
//Both are the same.
External Storage Class:
Because these variables are defined externally to the function, they can be used anywhere inside the function, making them universally applicable. Their starting value is zero. Their lifetime is equivalent to the duration of the programme because they can be used at any moment. It’s not usually a good idea to have too many global variables in a programme because they can compromise security.
Extern Keyword:
Use of the extern keyword tells the compiler that the variable has previously been defined somewhere else. By doing this, we may access the same variable in another file without allocating new memory and use it with the same space. Since we must use the extern keyword and it will automatically access it from the other file, its syntax is straightforward.
Syntax:
extern int a;
Static Storage Class:
Static variables are a little more technical because they are only valid for the function they are initialised in throughout the entire programme. It is useful when we modify the program’s value since the new value will be stored and overwritten by the old one. Their syntax is relatively simple because we just need to apply the Static keyword during initialization, and their initial default value is 0.
Syntax:
static int a;
Register Storage Class:
As its scope is restricted to the function it is defined in, its initial default value is 0, and its lifetime is limited to the end of the function block, the Register Storage Class is very similar to the Auto Storage Class. Now, the main distinction between it and the others is that it seeks rapid access to the CPU’s register memory rather than the local memory. It is typically used for programmes that must be accessed more quickly than others or that are frequently used.
Syntax:
register int a;