Storage Classes extern and register in C

For Complete YouTube Video: Click Here

In this class, we will understand Storage Classes extern and register in C.

We have already discussed the concepts of auto and static storage classes.

Storage Classes extern and register in C

extern Storage Class

The extern keyword is to extend the visibility of variables/functions.

Before understanding the concept of extern, we will recap the concept of declaring a variable and defining a variable.

Declaring a variable means we will not allocate the memory for the variable.

Defining a variable means memory will get allocated.

Coming back to the concept of extern, the extern storage class is not frequent.

The use of extern is frequent when we are developing a project.

The image below is the program to illustrate the extern storage class.

Storage Classes extern and register in C Example
Storage Classes extern and register in C Example

In the above example, we have two files by name firstfile.c and other.c.

In the other.c file, we have defined variable ‘a’ and initialized a value five.

Now, in the firstfile.c, we want to use the variable ‘a’s value.

We have to declare the variable done by using the extern storage class.

Using the extern storage class means we have defined the variable or function elsewhere, and we are using it here.

register Storage Class

The register storage class hints to the compiler to put the variable in a register.

The image is the definition of a variable using the register storage class.

Storage Classes extern and register in C register Definition
Storage Classes extern and register in C register Definition

It is a compiler choice to put it in a register or not.

So far, we have discussed that all the variables in the program get stored in the RAM.

But there is a possibility to store the variables in registers.

In precise, a register is a device faster than RAM.

When the program uses a variable value frequently, the programmer can ask the compiler to put it in a register.

But this allocation is done if the computer has such kind registers.

If not, the variables will be in the RAM.