What are the different storage classes in C?

28 Dec 2022 Balmiki Mandal 0 C Programming

There are four different storage classes in C

  • Automatic: Automatic variables are declared inside a function or block, and they are stored on the stack. They are destroyed when the function or block exits.
  • External: External variables are declared outside of any function or block, and they are stored in the data segment of the program. They have global scope and can be accessed from anywhere in the program.
  • Static: Static variables can be declared inside or outside of a function or block. If they are declared inside a function, they have local scope but they are not destroyed when the function exits. If they are declared outside of a function, they have global scope and are initialized to zero.
  • Register: Register variables are stored in the CPU's registers, which allows for faster access. However, the compiler is free to allocate register variables to other variables, so it is not guaranteed that a register variable will actually be stored in a register.

Table that summarizes the key features of each storage class:

Storage class Scope Lifetime Initialization
Automatic Local Function or block Automatic
External Global Program Manual
Static Local or global Program Manual or zero
Register Local Function or block Automatic
 

It is important to note that the register storage class is not guaranteed to be supported by all compilers.

How to use the different storage classes in C:

C Programming
// Automatic variable example
void my_function() {
  int x; // Automatic variable
  x = 10;
  printf("%d\n", x);
}

// External variable example
int global_variable = 20;

// Static variable example
static int static_variable = 30;

// Register variable example
register int register_variable = 40;

int main() {
  my_function(); // Prints 10
  printf("%d\n", global_variable); // Prints 20
  printf("%d\n", static_variable); // Prints 30
  printf("%d\n", register_variable); // Prints 40
  return 0;
}

Output:

10
20
30
40

The storage class of a variable can have a significant impact on the program's efficiency and behavior. It is important to choose the correct storage class for each variable.

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.