Chapter 14Beginner

Storage Classes in C

Control how variables live and where they are stored. Learn auto, static, register, and extern - the four storage classes in C.

18 min readUpdated 2024-12-16
storage classautostaticregisterexternscopelifetime

What You Will Learn

  • Know all 4 storage classes
  • Understand variable scope and lifetime
  • Share variables across files with extern
  • Choose the right storage class

01What are Storage Classes?

📦 Definition

Storage classes define where a variable is stored, how long it lives, and who can access it. They help us trace the existence of a variable during program runtime.

🎯 Storage Classes Control 4 Things

📍 Storage Location

Where is the variable stored? (RAM, CPU Register)

⏰ Lifetime

How long does the variable exist? (Block, Program)

👁️ Scope/Visibility

Where can you use it? (Local, Global, File)

🔢 Default Value

What's the initial value? (0, Garbage)

The 4 Storage Classes in C

KeywordStorageScopeLifetimeDefault
autoRAM (Stack)LocalEnd of blockGarbage
staticRAM (Data)Local/FileEnd of program0
registerCPU RegisterLocalEnd of blockGarbage
externRAM (Data)GlobalEnd of program0

💡 Scope vs Storage Class

Scope defines where a variable can be used. Storage class defines how long it lasts and where it's stored.

02auto - Automatic Storage

📝 What is auto?

auto is the default storage class for all local variables. Variables are created when the block starts and destroyed when it ends. You rarely need to write it explicitly!

PropertyValue
Storage LocationRAM (Stack)
ScopeLocal (within block/function)
LifetimeUntil block/function ends
Default ValueGarbage (unpredictable)
auto_example.c
C
1#include <stdio.h>
2
3int main() {
4 // These two declarations are IDENTICAL:
5 auto int x = 10; // Explicit auto
6 int y = 20; // Implicit auto (default)
7
8 printf("x = %d\n", x);
9 printf("y = %d\n", y);
10
11 // x and y are destroyed here
12 return 0;
13}
Output

x = 10

y = 20

💡 When to Use auto?

Almost never! All local variables are auto by default. The keyword is mainly for historical compatibility.

03static - Persistent Storage

📝 What is static?

static variables preserve their valueeven after the function ends! They are initialized only onceand exist for the entire program.

📖 For detailed examples, see the Static Keyword Tutorial.

PropertyValue
Storage LocationRAM (Data Segment)
ScopeLocal (but value persists)
LifetimeEntire program
Default Value0

Static Local Variable - Value Persists!

static_local.c
C
1#include <stdio.h>
2
3void counter() {
4 // Initialized only ONCE, value persists!
5 static int count = 0;
6 count++;
7 printf("Count = %d\n", count);
8}
9
10int main() {
11 counter(); // Count = 1
12 counter(); // Count = 2
13 counter(); // Count = 3
14 return 0;
15}
Output

Count = 1

Count = 2

Count = 3

❌ Without static

int count = 0;

✅ With static

static int count = 0;

Static Global Variable - File Private

When static is applied to a global variable or function, it becomes private to that file. Other files cannot access it!

static_global.c
C
1// file1.c
2static int secret = 42; // Only visible in file1.c
3
4static void helper() { // Only callable from file1.c
5 printf("Helper called\n");
6}
7
8// file2.c
9// Cannot access 'secret' or 'helper()' here!

💡 Two Uses of static

  • Local static: Value persists between function calls
  • Global static: Variable/function is private to file

04register - Fast Access (Hint)

📝 What is register?

register suggestsstoring the variable in a CPU register for faster access. But the compiler may ignore this hint!

PropertyValue
Storage LocationCPU Register (or RAM)
ScopeLocal
LifetimeUntil block ends
Default ValueGarbage
Can use & operator?NO!
register_example.c
C
1#include <stdio.h>
2
3int main() {
4 // Suggest storing in CPU register
5 register int i;
6
7 for (i = 0; i < 5; i++) {
8 printf("%d ", i);
9 }
10
11 // This would cause ERROR:
12 // int *ptr = &i; // Cannot take address!
13
14 return 0;
15}
Output

0 1 2 3 4

⚠️ Limitations of register

  • • Cannot use & (address-of) operator
  • • Compiler may ignore the suggestion
  • • Limited CPU registers available

💡 Modern Advice

register is mostly obsolete. Modern compilers automatically optimize which variables to keep in registers. You rarely need to use it!

05extern - External Linkage

📝 What is extern?

extern declares that a variable is defined in another file. It allows multiple files to share the same global variable.

PropertyValue
Storage LocationRAM (Data Segment)
ScopeGlobal (all files)
LifetimeEntire program
Default Value0

Sharing Variables Between Files

📁 main.c

main.c
C
1#include <stdio.h>
2
3// Define the variable here
4int globalVar = 100;
5
6void printVar(); // Declared elsewhere
7
8int main() {
9 printf("In main: %d\n", globalVar);
10 printVar();
11 return 0;
12}

📁 print.c

print.c
C
1#include <stdio.h>
2
3// Declare: defined elsewhere!
4extern int globalVar;
5
6void printVar() {
7 printf("In print: %d\n", globalVar);
8}

Compile both files together:

gcc main.c print.c -o program
Output

In main: 100

In print: 100

💡 extern Rules

  • extern declares a variable (no memory allocated)
  • • The variable must be defined (without extern) somewhere
  • • Cannot initialize with extern: extern int x = 5;

06Complete Comparison

Storage ClassKeywordStorageScopeLifetimeDefault
AutomaticautoStackLocalBlockGarbage
StaticstaticDataLocal/FileProgram0
RegisterregisterCPU RegLocalBlockGarbage
ExternalexternDataGlobalProgram0

Memory Layout Visualization:

High Address
STACK
auto, register variables
↕ Free ↕
HEAP
malloc, dynamic memory
DATA SEGMENT
static, extern, global
CODE
Low Address

07Common Mistakes

❌ Using Uninitialized auto Variables

int x;

printf("%d", x);

int x = 0;

printf("%d", x);

❌ Taking Address of register Variable

register int x = 5;

int *p = &x;

❌ Initializing extern Variable

extern int x = 5;

extern int x;

int x = 5;

❌ Confusing static Local vs Global

static inside function: value persists.
static outside function: file-private.

08Summary

🎯 Key Takeaways

  • auto: Default for locals, rarely used explicitly
  • static: Value persists (local) or file-private (global)
  • register: Hint for CPU register, mostly obsolete
  • extern: Share variables between files

int x;

static int y;

register int z;

extern int w;

08Next Steps

Now learn about arrays to store collections of data: