C Storage Classes

In C programming, storage classes are used to specify the lifetime, scope, and visibility of variables and functions. There are four types of storage classes in C programming: automatic, static, register, and extern.

Automatic Storage Class:

The automatic storage class is the default storage class for all local variables declared within a function. Automatic variables are created when a function is called and destroyed when the function returns. Automatic variables are stored on the stack and are not initialized by default.

void func()
{
   int a = 10;       // automatic variable
   printf("%d", a);
}

Static Storage Class:

The static storage class is used to declare variables that retain their value between function calls. Static variables are created when a program starts and destroyed when the program ends. Static variables are stored in the data segment of memory and are initialized to zero by default.

void func()
{
   static int a = 10;   // static variable
   printf("%d", a);
   a++;
}

In this example, the value of the static variable a is retained between function calls.

Register Storage Class:

The register storage class is used to declare variables that are stored in CPU registers instead of memory. Register variables are faster to access than variables stored in memory, but their use is limited because there are a limited number of CPU registers available. Register variables are declared using the register keyword.

For example:

void func()
{
   register int a = 10;   // register variable
   printf("%d", a);
}

Extern Storage Class:

  1. The extern storage class is used to declare variables or functions that are defined in another file. Extern variables and functions are declared using the extern keyword.

For example:

extern int a;   // external variable declaration
extern void func();   // external function declaration

The actual definition of the external variable or function is provided in another file.

Storage classes are important in C programming because they allow you to control the lifetime, scope, and visibility of variables and functions