Storage Classes in C

by S P SHARMA SIR

Thu Feb 27, 2025

Storage Classes in C

Storage classes in C define the scope, lifetime, Default Initial Value and visibility of variables and functions. There are four main storage classes in C:


Storage  Class            Keyword                Scope/Lifetime               Default Initial Value
AutomaticautoBlockUntil block exitsGarbage (undefined)
RegisterregisterBlockUntil block exitsGarbage (undefined)
StaticstaticFile/BlockProgram lifetimeZero (if not initialized)
ExternalexternGlobalProgram lifetimeZero (if not initialized)

1. auto (Automatic Storage Class)

  • Keyword: auto
  • Scope: Within block
  • Lifetime: Until block exits
  • Default Initial Value: Garbage (undefined)
  • Use Case: Default for local variables
  • Default for local variables inside functions.
  • Memory allocated on the stack.
  • Scope is limited to the block where it's declared.
  • Since auto is the default for local variables, we rarely use it explicitly.

2. register (Register Storage Class)

  • Keyword: register
  • Scope: Within block
  • Lifetime: Until block exits
  • Default Initial Value: Garbage (undefined)
  • Use Case: Faster access (loop counters)
  • Suggests that the variable be stored in a CPU register (faster access).
  • Used for high-speed variables, like loop counters.
  • Cannot take the address (&) of a register variable.
  • Modern compilers often ignore register, as they optimize automatically.

3. static (Static Storage Class)

  • Retains its value between function calls.
  • Can be used in local or global scope.
  • Unlike normal global variables, static global variables cannot be accessed in other files.

(a) Static Local Variables

  • Maintains value between function calls.

(b) Static Global Variables

  • Limited only to the file where they are defined.

4. extern (External Storage Class)

  • Used to access global variables from another file.
  • Declares a variable without defining it (allocated elsewhere).



S P SHARMA CLASSES