C Storage Classes

Storage Classes: auto, extern, static, register.

Storage Classes

Storage classes are used to define the scope, lifetime, and visibility of variables and functions. There are four primary storage classes in C:

auto

Variables declared with the 'auto' storage class are typically used for local variables within a function. They have automatic storage duration, which means they are created when the function is called and destroyed when the function exits. The 'auto' keyword is rarely used explicitly, as it is the default storage class for local variables.

void func() {
    auto int x = 10; // 'auto' is optional here
}

extern

The 'extern' storage class is used to declare variables or functions that are defined in other source files or at a later point in the program. It indicates that the variable or function is defined elsewhere and should be used in the current file.

extern int x; // Declare a global variable
extern void func(); // Declare a function defined in another file

static

Variables and functions declared with the 'static' storage class have a different meaning depending on where they are used.

  • Within a function, 'static' variables have a longer lifetime than automatic variables and retain their values between function calls.

void func() {
    static int x = 0; // Variable 'x' retains its value between calls
    x++;
}
  • When used at the global level (outside of any function), static variables and functions are limited in visibility to the current file. They are not accessible from other files.

static int x = 42; // Limited to the current file
static void func() {
    // This function is also limited to the current file
}

register

The 'register' storage class is a hint to the compiler to store the variable in a CPU register for faster access. However, in modern compilers, this hint is often ignored because modern compilers are typically better at optimizing code placement than programmers.

register int x = 100; // Compiler use a register 'x'

Note: It's important to note that the use of these storage classes can affect the behavior and performance of your C program. The choice of which storage class to use depends on the specific requirements and constraints of your program.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.