Storage Classes auto and static in C

For Complete YouTube Video: Click Here

In this class, we will understand Storage Classes auto and static in C.

We have already discussed the concept of the scope of a variable.

Based on that discussion, we will discuss storage classes.

Storage Classes auto and static in C

Storage Classes describe the scope, visibility, and lifetime features of a variable or function.

There are four types of storage classes

  1. auto
  2. static
  3. extern 
  4. register

auto Storage Class

auto is the default storage class for all the variables declared inside a function or a block.

The image below is the use of the auto storage class.

Storage Classes auto and static in C
Storage Classes auto and static in C auto Example

By default, a variable declared is of the auto storage class.

auto storage class declaration means the variables automatically will die after the scope of the variable.

The declaration of a variable with auto or without the auto storage class does not make any difference.

static Storage Class

Static storage class preserves their value even after they are out of their scope.

The image below is a programming example with the static declaration.

Storage Classes auto and static in C static Example
Storage Classes auto and static in C static Example

In the above example, in function fun, the count variable is declared as static.

The image below is the process diagram.

Understanding Local and Global Variables in C Process for a Program Process
Understanding Process for a Program Process

The static variables will get declared in the data part of the process where the global variables are declared.

In the ‘main function,’ the static variable will get initialized when we call the fun function call for the first time.

In the fun function, the count is increment by 1. count is 1.

The second print function, the fun function, is called again.

The point to understand is whenever a variable is static. It will get initialized only once.

The count will get incremented y 1. count is 2.

Even though we came out of the scope of the variable static variable value is preserved.