📘 Storage Classes in C Programming

auto, static, extern, register Explained with Memory, Scope & Lifetime (Complete Guide)


🧑‍💻 Introduction

In C programming, variables don’t just store values — they also have:

  • 📍 Scope (Where can it be accessed?)

  • ⏳ Lifetime (How long does it exist?)

  • 💾 Memory Location (Stack / Data Segment / CPU Register)

👉 To control these properties, C provides Storage Classes.

Storage classes tell the compiler:

“Where to store the variable and how long to keep it alive.”

There are 4 storage classes in C:

  1. auto

  2. static

  3. extern

  4. register

Let’s understand each one step-by-step.


📌 Real-Life Analogy (Add This After Introduction)

📌 Think of variables like employees in a company:

  • auto → Temporary worker (works only during project time)

  • static → Permanent employee (remains in company)

  • extern → Employee from another branch

  • register → Super-fast assistant sitting beside you

This makes the concept very easy to understand 😄


🧠 1️⃣ auto Storage Class

🔹 Default for Local Variables

If you write:

int x; // Declare a variable named 'x' of type integer (can store whole numbers)

It is automatically:

auto int x; // Declare a variable 'x' of type int with automatic storage duration (default for local variables)

📍 Properties

  • Scope → Inside block only

  • Lifetime → Till function executes

  • Memory → Stack


✅ Example Program

#include <stdio.h> // Include standard I/O library for printf() void display() { // Function 'display' definition auto int x = 10; // Declare an automatic integer 'x' and initialize to 10 printf("Value of x: %d\n", x); // Print the value of x } int main() { // Main function: program execution starts here display(); // Call the display() function return 0; // Return 0 to indicate successful execution }

💡 Explanation

  • x exists only inside display()

  • Once function ends → x is destroyed

🔎 Output:

Value of x: 10

🧠 2️⃣ static Storage Class

Static variables preserve their value between function calls.


🔹 Case 1: static Local Variable

#include <stdio.h> // Include standard I/O library for printf() void counter() { // Function 'counter' definition static int count = 0; // Declare a static integer 'count', initialized to 0 (retains value between function calls) count++; // Increment 'count' by 1 printf("Count: %d\n", count); // Print the current value of 'count' } int main() { // Main function: program execution starts here counter(); // Call counter() → count becomes 1 counter(); // Call counter() → count becomes 2 counter(); // Call counter() → count becomes 3 return 0; // Return 0 to indicate successful execution }

🔎 Output:

Count: 1
Count: 2
Count: 3

💡 Why?

Because static variable:

  • Is created only once

  • Retains value

  • Stored in Data Segment (not stack)


🔹 Case 2: static Global Variable

When declared outside functions:

static int x = 100; // Declare a static integer 'x' with initial value 100; retains its value throughout the program and has internal linkage if outside a function

👉 It cannot be accessed from other files.


🧠 3️⃣ extern Storage Class

Used to access global variable from another file.


📁 File1.c

int number = 50; // Declare an integer variable 'number' and initialize it with 50

📁 File2.c

#include <stdio.h> // Include standard I/O library for printf() extern int number; // Declare 'number' as an external variable (defined in another file) int main() { // Main function: program execution starts here printf("%d", number); // Print the value of external variable 'number' return 0; // Return 0 to indicate successful execution }

💡 Explanation

  • extern does NOT create new variable

  • It only refers to existing global variable

  • Used in multi-file programs


🧠 4️⃣ register Storage Class

Requests compiler to store variable in CPU register.

#include <stdio.h> // Include standard I/O library for printf() int main() { // Main function: program execution starts here register int i; // Declare 'i' as a register variable (suggests storing in CPU register for faster access) for(i = 0; i < 5; i++) { // Loop from i = 0 to i < 5, incrementing i by 1 each iteration printf("%d ", i); // Print the current value of i followed by a space } return 0; // Return 0 to indicate successful execution }

📍 Properties

  • Stored in CPU register (if available)

  • Faster access

  • Cannot use & operator

register int x;
printf("%p", &x); // ❌ ERROR

🔎 Output:

0 1 2 3 4

📊 Scope & Lifetime Comparison Table

Storage Class Scope Lifetime Memory Location
auto Block Till function ends Stack
static Block / File Entire program Data Segment
extern Global Entire program Data Segment
register Block Till function ends CPU Register


🧠 Memory Layout of C Program




🧪 Practice Section – Storage Classes in C

Below are 5 important practice programs to strengthen your understanding.


🧪 Program 1️⃣ – Demonstrate auto Variable

#include <stdio.h> // Include standard input-output header file

void test() // Function definition
{
auto int x = 5; // auto variable (default for local variables)
printf("Value of x: %d\n", x); // Print value of x
}

int main() // Main function
{
test(); // Call function
test(); // Call function again
return 0; // Return 0 to OS
}

🔎 Concept:

  • auto variable is recreated every time function runs.

  • Value does NOT persist.

🔎 Output:

Value of x: 5
Value of x: 5

🧪 Program 2️⃣ – Static Local Variable Example

#include <stdio.h> // Include standard I/O library for printf() void test() // Define function 'test' { static int x = 10; // Declare a static integer 'x', initialized only once; retains its value between function calls x += 5; // Increment x by 5; value persists across calls printf("Value: %d\n", x); // Print the current value of x } int main() // Main function: program execution starts here { test(); // Call test() → x = 15, prints 15 test(); // Call test() again → x = 20, prints 20 test(); // Call test() again → x = 25, prints 25 return 0; // Return 0 to OS, indicating successful execution }

🔎 Concept:

  • Static variable retains value.

  • Created only once.

  • Stored in Data Segment.

🔎 Output:

Value: 15
Value: 20
Value: 25

🧪 Program 3️⃣ – Static Global Variable

#include <stdio.h> // Include standard library

static int num = 100; // Static global variable (file scope)

int main() // Main function
{
printf("Value of num: %d", num); // Print global variable
return 0; // End program
}

🔎 Concept:

  • Accessible only within same file.

  • Cannot be accessed in other files.

🔎 Output:

Value of num: 100

🧪 Program 4️⃣ – Extern Variable Example

(Conceptual multi-file example)

📁 File1.c

int value = 200; // Global variable defined here

📁 File2.c

#include <stdio.h> // Include standard library

extern int value; // Declare external variable

int main() // Main function
{
printf("Value: %d", value); // Access value from File1
return 0; // End program
}

🔎 Concept:

  • extern does not create memory.

  • It links variable from another file.

🔎 Output:

Value: 200

🧪 Program 5️⃣ – Register Variable Example

#include <stdio.h> // Include standard library

int main() // Main function
{
register int i; // Register variable (stored in CPU register if possible)

for(i = 1; i <= 5; i++) // Loop from 1 to 5
{
printf("%d ", i); // Print value
}

return 0; // End program
}

🔎 Important Note:

You cannot use address operator with register variable:

register int x; // Declare register variable
printf("%p", &x); // ❌ Error (Address not allowed)

🔎 Output:

1 2 3 4 5


🎯 Viva Questions (Very Important)

1️⃣ What is storage class in C?

A storage class in C defines the scope, lifetime, and memory location of a variable.
It tells the compiler where to store the variable (stack, data segment, or register) and how long it should exist.
C provides four storage classes: auto, static, extern, and register.
They help control variable behavior inside a program.


2️⃣ What is default storage class of local variable?

The default storage class of a local variable is auto.
If we declare int x; inside a function, it is automatically treated as auto int x;.
It is stored in the stack memory.
Its lifetime is limited to the block in which it is declared.


3️⃣ Difference between static and auto?

Feature auto static
Definition Default storage class for local variables Storage class that preserves value between function calls
Scope Limited to the block or function where declared Limited to block (if local) or file (if global)
Lifetime Exists only during function execution Exists for entire program execution
Memory Location Stack memory Data Segment
Value Retention Value is lost after function ends Value is preserved between function calls
Initialization Not automatically initialized (may contain garbage value) Automatically initialized to 0 if not explicitly initialized
Recreation Recreated every time function is called Created only once
Usage Purpose Used for temporary variables Used when we need to remember previous value

4️⃣ Can we access static global variable in another file?

No, we cannot access a static global variable from another file.
When a global variable is declared as static, its scope becomes limited to that file only.
It provides internal linkage.
This improves data security in multi-file programs.


5️⃣ What is extern used for?

The extern keyword is used to declare a global variable that is defined in another file.
It does not create new memory for the variable.
It simply tells the compiler that the variable exists somewhere else.
It is mainly used in multi-file programming.


6️⃣ Why can’t we use & with register?

Register variables are stored in CPU registers instead of memory (if possible).
Since registers do not have a memory address like RAM, the address operator & cannot be used.
Trying to use & with a register variable results in a compilation error.
This is a limitation of the register storage class.


7️⃣ Where are static variables stored?

Static variables are stored in the Data Segment of memory.
They are not stored in the stack.
They exist for the entire duration of the program.
Their value is preserved between function calls.


8️⃣ What is scope vs lifetime?

Scope refers to the region of the program where a variable can be accessed.
Lifetime refers to how long the variable exists in memory during program execution.
Scope is about accessibility.
Lifetime is about memory duration.


9️⃣ Does static variable reinitialize?

No, a static variable is initialized only once.
Even if the function is called multiple times, the variable retains its previous value.
It is not recreated each time like an auto variable.
This makes static variables useful for counters.


🔟 Can register variable be global?

No, register variables cannot be declared as global variables.
The register storage class is allowed only for local variables.
This is because CPU registers are meant for fast local access.
Global variables must reside in memory, not registers.


📝 MCQs (For Engagement)

1️⃣ Default storage class of local variable is:

a) static
b) extern
c) auto ✅
d) register

Explanation: Local variables are auto by default and stored in stack memory.


2️⃣ Static variable is stored in:

a) Stack
b) Heap
c) Data Segment ✅
d) CPU

Explanation: Static variables are stored in the data segment and exist throughout the program.


3️⃣ Which storage class allows access across files?

a) auto
b) static
c) extern ✅
d) register

Explanation: Extern is used to access global variables defined in another file.


4️⃣ What is the lifetime of a static variable?

a) Until function ends
b) Until block ends
c) Entire program execution ✅
d) Only during compilation

Explanation: Static variables remain in memory for the entire execution of the program.


5️⃣ Where are auto variables stored?

a) Data Segment
b) Stack ✅
c) Heap
d) CPU Register

Explanation: Auto variables are created in stack memory and destroyed after function ends.


6️⃣ What happens if extern variable is declared but not defined anywhere?

a) Program runs normally
b) Compiler ignores it
c) Compilation error
d) Linker error ✅

Explanation: If extern variable is not defined, linker cannot find its memory location.


7️⃣ Which storage class retains value between function calls?

a) auto
b) register
c) static ✅
d) extern

Explanation: Static variables preserve their value between multiple function calls.


8️⃣ Which storage class cannot use address operator (&)?

a) auto
b) static
c) extern
d) register ✅

Explanation: Register variables may not have a memory address, so & operator is not allowed.


⚠ Common Mistakes Students Make

  • Thinking static variable is recreated every time ❌

  • Using extern without defining variable anywhere ❌

  • Trying to access static global variable from another file ❌

  • Using & with register variable ❌


🎓 Conclusion

Storage classes in C are fundamental to understanding how variables behave inside a program. They control three critical aspects:

  • 📍 Scope (Where a variable can be accessed)

  • ⏳ Lifetime (How long a variable exists)

  • 💾 Memory Location (Stack, Data Segment, or CPU Register)

By mastering auto, static, extern, and register, you now clearly understand how C internally manages variable storage and memory organization.

This concept is extremely important for:

  • 🎯 Technical interviews

  • 🎓 University exams & viva

  • 🧠 Writing efficient and optimized programs

  • 💻 Advanced system-level and multi-file programming

Once you fully understand storage classes, you gain deeper control over memory behavior in C — which separates beginners from confident C programmers.


📌 Keep Learning. Keep Coding. Keep Growing.

✨ Written by Krishna Popat
🌱 Founder, Learning Growth Hub

Comments

Popular posts from this blog

🌟 The Honest Journey of a Student: Learning, Failing, and Growing

“C Programming for Beginners: Master Variables, Data Types, and Memory (Bits Explained)”