Skip to content

Storage classes in C

2024-02-29

In C, storage classes determine the scope, visibility, and lifetime of variables or objects. C provides four storage classes:

  1. Automatic (auto):

    • Variables declared as auto are allocated memory automatically on the stack.
    • They have a local scope, limited to the block or function in which they are declared.
    • Their lifetime is limited to the duration of the block or function.
    • If no storage class is specified for a variable declared within a block, it is treated as auto by default.
  2. Register (register):

    • Variables declared as register are stored in CPU registers for faster access.
    • They have a local scope, limited to the block or function in which they are declared.
    • Their lifetime is limited to the duration of the block or function.
    • The register storage class is a hint to the compiler to optimize the storage of the variable in a CPU register, but the compiler may or may not actually store the variable in a register, as it has the final decision.
  3. Static (static):

    • Variables declared as static are allocated memory in the data segment of the program, not on the stack.
    • They have a local scope, limited to the block or function in which they are declared.
    • Their lifetime is throughout the execution of the program.
    • The value of a static variable persists between function calls, meaning that its value is retained even after the function returns.
    • Static variables are initialized only once, during program execution, and retain their values until the program terminates.
  4. Extern (extern):

    • Variables declared as extern are used to refer to global variables that are defined in another source file.
    • They have a global scope, visible across multiple files in a program.
    • Their memory is allocated in the data segment of the program, and they are not associated with any particular function or block.
    • Their lifetime is throughout the execution of the program.
    • extern variables must be defined in a separate source file, and only their declarations are provided in other source files where they are used.

Understanding and proper use of storage classes in C can help in managing the memory and scope of variables effectively in a program, and ensure correct behavior and performance.