C programming - Storage class

https:/‮igi.www/‬ftidea.com

In C programming, a storage class is a keyword that determines the scope, lifetime, and visibility of a variable or function within a program. There are four storage classes in C:

  1. auto: This is the default storage class for local variables. Variables declared with the auto keyword have a local scope and are automatically destroyed when the block in which they are declared exits.

  2. register: This storage class is used to define local variables that are stored in the CPU registers for faster access. However, it's up to the compiler to decide whether to use a register for the variable or not. Variables declared with the register keyword have a local scope and are automatically destroyed when the block in which they are declared exits.

  3. static: This storage class is used to define variables that retain their value between function calls. Static variables are initialized to zero by default and retain their value until the program terminates. Variables declared with the static keyword have a local scope but are not destroyed when the block in which they are declared exits.

  4. extern: This storage class is used to define variables and functions that are defined in other files. The extern keyword tells the compiler that the variable or function is defined somewhere else and prevents the compiler from allocating memory for it. Variables declared with the extern keyword have a global scope.

The following example shows how to declare variables with different storage classes:

#include <stdio.h>

int main() {
   auto int a;         // local variable, destroyed when function exits
   register int b;    // local variable, stored in CPU register
   static int c;      // local variable, retains its value between function calls
   extern int d;      // variable defined in another file

   printf("Size of auto variable: %ld bytes\n", sizeof(a));
   printf("Size of register variable: %ld bytes\n", sizeof(b));
   printf("Size of static variable: %ld bytes\n", sizeof(c));
   printf("Value of extern variable: %d\n", d);

   return 0;
}

It's important to note that the storage class of a variable affects its scope, lifetime, and visibility. Understanding these concepts is important for writing efficient and reliable C programs.