C Storage Classes

C Storage Classes: Controlling Variable Scope and Lifetime

In C, a Storage Class defines the scope (visibility) and lifetime (how long it stays in memory) of variables and/or functions.

There are four main storage classes in C:

  1. auto
  2. extern
  3. static
  4. register

1. The auto Storage Class

auto is the default storage class for all local variables defined within a function or block. They are created when the block is entered and destroyed when the block is exited.

void myFunction() {
    int x = 10;      // This is an auto variable by default
    auto int y = 20; // Explicitly defining it as auto (rarely done)
}

2. The static Storage Class

The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope.

This makes static variables excellent for maintaining state across function calls!

Static Variable Example:

#include <stdio.h>

void counterFunction() { static int count = 0; // Initialized only once count++; printf("Count is %d\n", count); }

int main() { counterFunction(); // Count is 1 counterFunction(); // Count is 2 counterFunction(); // Count is 3 return 0; }


3. The extern Storage Class

The extern storage class is used to give a reference of a global variable that is visible to ALL the program files. When you use extern, the variable cannot be initialized; it just points the variable name at a storage location that has been previously defined in another file.


Exercise

?

Which storage class preserves the value of a local variable between function calls?