Storage Classes in C

Till now we have declared the variables in its simplest form. Declaration of variables contains two parts.

Data type of the variable

Storage of the variable

Till now we are just declaring the data type of the variable.

Does it mean there is no storage class of variables which we have declared till now?
Well the answer is definitely No, because we cannot declare a variable without its storage class. By default certain storage classes automatically added, if we don’t declare storage classes explicitly.

What are storage classes In C?

As I told you earlier, during the declaration of variables some space is reserved for that variable. Storage class is the property which decides that reserved space. There are two places where space is reserved for variables. One is memory and the other is register.

Storage class of the variable defines

Place where the variable should store

Default or initial value of the variable

Scope of the variable

Life of the variable

There are four storage classes in C language and I will define all of them based on the above factors.

Automatic Storage Class

Storage: MemoryInitial Value: Any garbage valueScope: Local to the block in which the variable is definedLife: Till the control remains in the block in which it is defined

Syntax: auto int x;

1

2

3

4

5

6

intmain()

{

auto intx;//automatic variable

inty;//this is also automatic variable

return0;

}

If we do not specify the storage class of a variable then by default it is in automatic storage class. You can see this in above example.

Register Storage Class

Storage: CPU registers.Initial value: Any garbage value Scope: Local to the block in which the variable is definedLife: Till the control remains in the block in which it is defined

Syntax: register int x;

A variable defined as register is stored in CPU registers. We define a variable as register when we need to access it frequently in our program. Since registers are limited so when no register is available then the variable is stored in memory.

Static Storage Class

Storage: MemoryInitial value: 0 (zero)Scope: Local to the block in which the variable is defined Life: Variable exists during the various function calls

Syntax: static int x;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include<stdio.h>

voidfun()

{

staticintx;// x is static variable

printf("%d ",x);

x=x+2;

}

intmain()

{

fun();

fun();

fun();

return0;

}

Output0 2 4

In the above program I have declared x variable as static, its initial value is 0. I have called the fun() function there times. I am increasing the value of x by 2. You can see in the output that the value of x variable is not lost. It remains in the memory during different function calls.

External Storage Class

A variable with external storage class can be defined outside all functions. So that it will be available for every function throughout the program execution. It can also be defined inside certain function.