• Home
  • Storage Classes in C

Storage Classes in C

In C language, a storage class specifies the visibility and lifetime of a variable or function. There are four storage classes in C:

auto: The auto storage class is the default storage class for variables declared within a function. Variables of this class are local to the function in which they are defined and are automatically initialized to zero when the function is called. They are destroyed when the function returns.

register: The register storage class is used for variables that are used frequently in a program. These variables are stored in a CPU register for faster access, which can improve the performance of the program. The register storage class is generally used for variables that are used in a loop or for variables that are accessed frequently.

static: The static storage class is used for variables that are local to a function and are preserved between function calls. These variables are initialized to zero when the program starts and retain their value between function calls. They are destroyed when the program ends.

extern: The extern storage class is used for variables and functions that are defined in another file or in a different part of the same file. These variables and functions are called “external” and can be accessed from any part of the program. The extern storage class allows you to share variables and functions between files or modules.

Here is an example of using the different storage classes in C:

#include <stdio.h>

// global variable with the extern storage class
extern int x;

// function with the static storage class
static void foo() {
// do something

int main() {
// local variable with the auto storage class
auto int y = 0;

// local variable with the register storage class
register int z = 0;

// use the global variable
x = 10;

// call the function

return 0;

In this example, the global variable ‘x’ is defined with the extern storage class, the function ‘foo()’ is defined with the static storage class, and the local variables ‘y’ and ‘z’ are defined with the auto and register storage classes, respectively.

The storage class of a variable or function determines its visibility and lifetime in a program. It is important to choose the appropriate storage class based on the requirements of the program.