Storage Classes in C Programming (Complete Guide with Examples)


This tutorial explains storage classes in C, which determine scope, lifetime, and visibility of variables. It covers auto, register, static, and extern with practical examples to help beginners understand memory management and variable accessibility.

1. What are Storage Classes

  1. Storage classes define:
  2. Scope: Where a variable is accessible
  3. Lifetime: How long a variable exists in memory
  4. Visibility: Where it can be used in the program
  5. C supports four main storage classes:
  6. auto
  7. register
  8. static
  9. extern

2. auto Storage Class

  1. Default for local variables
  2. Stored in stack memory
  3. Lifetime: function execution
  4. Scope: within the block

Example:


#include <stdio.h>

int main() {
auto int a = 10;
printf("a = %d\n", a);
return 0;
}

Output:


a = 10

3. register Storage Class

  1. Suggests compiler to store variable in CPU register for faster access
  2. Only for local variables of small size (int, char)
  3. Cannot take address using &

Example:


#include <stdio.h>

int main() {
register int counter;
for(counter = 1; counter <= 5; counter++) {
printf("%d ", counter);
}
return 0;
}

Output:


1 2 3 4 5

4. static Storage Class

  1. Local static variable retains its value between function calls
  2. Default initial value is 0 if not assigned
  3. Can also be global static to limit scope to the file

Example:


#include <stdio.h>

void demo() {
static int count = 0;
count++;
printf("Count = %d\n", count);
}

int main() {
demo();
demo();
demo();
return 0;
}

Output:


Count = 1
Count = 2
Count = 3

Explanation:

  1. Value of count is retained between calls

5. extern Storage Class

  1. Refers to variables declared in another file or outside function
  2. Scope: global
  3. Lifetime: entire program execution

Example:


#include <stdio.h>

int x = 100; // global variable

void display();

int main() {
extern int x;
printf("x = %d\n", x);
display();
return 0;
}

void display() {
extern int x;
x += 50;
printf("x in display = %d\n", x);
}

Output:


x = 100
x in display = 150

Explanation:

  1. extern allows access to global variable x in multiple functions

6. Key Points to Remember

  1. auto: default local, stack memory
  2. register: fast access, local only
  3. static: retains value, local or file scope
  4. extern: global variable access across files/functions
  5. Storage classes help manage scope, lifetime, and memory efficiently