C ยท Chapter 39 of 45

C Storage Classes

Storage classes determine a variable's scope, lifetime and visibility across a program. C provides four storage class specifiers: auto, register, static, and extern.

Understanding storage classes helps control whether a variable is temporary, persists between function calls, or is shared across multiple source files.

Syntax
static type name;
extern type name;

auto and register

auto is the default for local variables (rarely written explicitly). register suggests to the compiler that a variable should be stored in a fast CPU register, though the compiler may ignore this hint.

static and extern

static inside a function makes a variable retain its value between calls. static at file scope limits a variable or function's visibility to that file. extern declares a variable defined in another file, allowing it to be shared.

Example 1 (c)
#include <stdio.h>

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

int main() {
  counter();
  counter();
  counter();
  return 0;
}
Output
1
2
3

static preserves count's value between calls instead of resetting it each time.

Example 2 (c)
// file1.c
int sharedValue = 100;

// file2.c
#include <stdio.h>
extern int sharedValue;

int main() {
  printf("%d\n", sharedValue);
  return 0;
}
Output
100

extern lets file2.c access a variable actually defined in file1.c.

Key points

  • auto is the default storage class for local variables.
  • static preserves a local variable's value between function calls.
  • static at file scope restricts visibility to that file only.
  • extern shares a variable's definition across multiple source files.
๐Ÿ’ก Note: A static local variable is initialized only once, the first time execution reaches its declaration.

๐Ÿ“ Quick Quiz

1. What does static do to a local variable?

2. What does extern allow?

3. What is the default storage class for a local variable?