← Back to C Course | Chapter 5: Functions | Lesson 7 of 8

C Storage Classes

Auto Storage Class

auto is the default storage class for any local variable you declare without specifying one explicitly -- it allocates temporary memory for the current function call and is destroyed automatically once that call ends.

Example: Auto Storage Class

c
#include <stdio.h>
int main() {
	auto int x = 5;
	printf("%d", x);
	return 0;
}

Register Storage Class

register asks the compiler to store a variable directly in a CPU register instead of regular memory (RAM), aiming for faster access -- though modern compilers usually make this optimization decision on their own regardless of the hint.

Example: Register Storage Class

c
#include <stdio.h>
int main() {
	register int i;
	for (i = 0; i < 3; i++) {
		printf("%d ", i);
	}
	return 0;
}

Static Storage Class

static changes a local variable's lifetime so it retains its value between separate calls to the same function, instead of resetting each time -- useful for things like a counter that needs to persist across multiple invocations.

Example: Static Storage Class

c
#include <stdio.h>
void counter() {
	static int count = 0;
	count++;
	printf("%d ", count);
}
int main() {
	counter();
	counter();
	counter();
	return 0;
}

Extern Storage Class

extern declares that a variable is defined in a different source file, letting multiple .c files share and modify the same global variable without each one needing its own separate copy.

Example: Extern Storage Class

c
#include <stdio.h>
int sharedValue = 42;
extern int sharedValue;
int main() {
	printf("%d", sharedValue);
	return 0;
}

Selecting Storage Classes

Choosing the right storage class is about matching intent to behavior: static for a value that must persist across calls, auto for ordinary short-lived locals, and register only as a rarely-needed performance hint on tight loop counters.

Example: Selecting Storage Classes

c
#include <stdio.h>
void counter() {
	static int persistent = 0;
	int temporary = 0;
	persistent++;
	temporary++;
	printf("%d %d ", persistent, temporary);
}
int main() {
	counter();
	counter();
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.