C Storage Classes

C Tutorial

C Storage Classes

Storage classes in C define the scope, lifetime, and visibility of variables and functions within a program.

They tell the compiler:

✔ Where the variable is stored
✔ How long the variable exists (lifetime)
✔ Who can access it (scope)
✔ What is its default value


🔹 Available Storage Classes in C

Storage ClassScopeLifetimeDefault ValueMemory Location
autoLocal (block)Function/block durationGarbage valueStack
registerLocalFunction/block durationGarbage valueCPU register (if available)
staticLocal or GlobalEntire program durationZeroMemory (Static/Data Segment)
externGlobalEntire program durationZeroMemory (Static/Data Segment)


1️⃣ auto (Automatic Storage)

  • Default for local variables

  • Exists only inside functions or blocks

  • Stored in stack memory


 

✔ Usually we don’t use auto keyword explicitly because it’s default.



2️⃣ register

  • Suggests storing variable in CPU register for faster access

  • Cannot take its memory address using &


 

❗ Note: Compiler may ignore this request.



3️⃣ static

A static variable preserves its value between function calls.

✔ Example: Local static variable


 

Output:

Count: 1
Count: 2
Count: 3

🔹 Unlike normal local variables, static does not reset.


✔ Static Global Variable

A static global variable is accessible only inside the file, not from other .c files.

static int number = 100; // File-level visibility only


4️⃣ extern

extern is used to declare a variable that is defined in another file or location.

Useful in multi-file projects.


📌 Example

📁 file1.c

#include <stdio.h>

int num = 10; // Definition

 

📁 file2.c


 

extern does not allocate memory — it only references existing storage.



🧠 Summary Table

KeywordUse Case
autoDefault local variable
registerFaster access storage suggestion
staticPersistent variable or file-level global variable
externGlobal variable sharing between files

Example Using All Storage Classes

#include <stdio.h>

int global = 5; // global variable

void show() {
static int count = 0; // static local variable
count++;
printf(“Static Count = %d\n”, count);
}

int main() {

auto int a = 10; // automatic local variable
register int r = 20; // register variable

extern int global; // refers to global variable

printf(“Auto: %d\n”, a);
printf(“Register: %d\n”, r);
printf(“Extern Global: %d\n”, global);

show();
show();
show();

return 0;
}

You may also like...