Unit 10: Storage Classes

Table of Contents

1. Introduction to Storage Classes

In C, every variable has two attributes: a type (like int or float) and a storage class. A storage class defines the scope (visibility) and lifetime of a variable within a program.

Definition: Storage classes tell the compiler where to store the variable, what the initial value is, and how long the variable exists.

2. Scope, Visibility, and Lifetime of Variables

Before diving into specific specifiers, it is critical to understand three key concepts:

3. Storage Class Specifiers

C provides four primary storage class specifiers:

Specifier Storage Initial Value Scope Lifetime
auto Stack (Memory) Garbage Local Function Block
register CPU Register Garbage Local Function Block
static Data Segment Zero Local/Global Entire Program
extern Data Segment Zero Global Entire Program

4. Automatic Storage Class (auto)

The auto storage class is the default for all local variables declared inside a function or block.

void function() {
    int x; // same as "auto int x;"
}
    

5. Register Storage Class (register)

The register specifier suggests to the compiler that the variable be stored in a CPU register instead of RAM for faster access.

register int counter;
    

6. Static Storage Class (static)

The static storage class instructs the compiler to keep a local variable in existence during the entire lifetime of the program.

Static Local Variables

Unlike auto variables, static local variables maintain their values between function calls.

void increment() {
    static int count = 0;
    count++;
    printf("%d", count);
}
// Calling increment() thrice will print 1, 2, 3.
    

Static Functions

When a function is declared as static, its scope is restricted to the file in which it is defined. This is used for encapsulation and data hiding.

7. External Storage Class (extern)

The extern storage class is used to give a reference to a global variable that is visible to all the program files.

// File1.c
int count = 5; 

// File2.c
extern int count; // Declares that count is defined elsewhere
void main() {
    printf("%d", count);
}
    

8. Const Qualifier

The const qualifier is used to declare variables whose value cannot be changed after initialization.

const float PI = 3.14;
// PI = 3.15; // This will cause a compilation error
    

9. Exam Focus Enhancements

Exam Tips
Common Mistakes
Frequently Asked Questions

Q: Can I use 'extern' inside a function?
A: Yes, it tells the function that the variable it is using is a global one defined either later in the same file or in another file.

Q: What is the difference between 'static global' and 'global'?
A: A regular global variable can be accessed by other files using extern. A static global variable is hidden from other files.

Q: Why use 'const' instead of '#define'?
A: const variables have a data type and follow scope rules, making them safer and easier to debug than #define macros.