STORAGE CLASSES IN C

Augustine Joseph
2 min readJun 10, 2024

--

In C programming, storage classes define how variables and functions are stored in memory, affecting their visibility (scope) and lifetime within the program. Here are the four main storage classes:

Automatic (default):

  • Variables declared within a block (curly braces {}) or function body.
  • Scope: Local to the block or function where they are declared.
  • Lifetime: Created when the block or function is entered, destroyed when it exits.
  • Use: For most local variables that only need to exist during a specific code section.
void doSomething() {
int x = 10; // Automatic variable
}

External:

  • Variables declared outside any block or function (typically at the beginning of a file).
  • Scope: Global, accessible from anywhere in the program (same file or linked files).
  • Lifetime: Entire program execution.
  • Use: For variables that need to be shared across multiple functions.
  • Excessive use of global variables can lead to code complexity and maintainability issues.
int global_count = 0; // External variable

void incrementCount() {
global_count++;
}

void printCount() {
printf("Count: %d\n", global_count);
}

Static:

Can be applied to both local and global variables.

  1. Local static:
  • Scope: Local to the block or function where they are declared.
  • Lifetime: Entire program execution. Value persists between function calls.
  • Use: For variables that need to retain their value across function calls within the same block/function.

2. Global static:

  • Scope: Limited to the file where they are declared (not truly global across files).
  • Lifetime: Entire program execution.
void rememberValue() {
static int value = 0; // Local static variable
value++;
printf("Value: %d\n", value);
}

int main() {
rememberValue(); // Prints 1
rememberValue(); // Prints 2 (value retains its state)
return 0;
}

Register:

  • Suggests the compiler to store the variable in a CPU register (faster access than memory).
  • Not a guarantee to store in register due to hardware limitations. The compiler decides based on hardware and optimization.
  • Use: For small, frequently accessed variables (like loop counters) to potentially improve performance.
  • Use sparingly, as it’s compiler-dependent and may affect perfomance.
register int count; 

--

--