Storage Classes: All Together
  • Twitter
  • Facebook
  • Snapchat
  • Instagram

C Program Combining Multiple Storage Classes and Explaining Their Interactions

📑 On this page:
  • What Happens When You Mix Them?
  • Simple Rules for Combining
  • Complete C Program
  • Program Output
  • Step-by-Step Explanation
  • Frequently Asked Questions
📚 In this program, you will learn:
  • How auto, static, extern, register, and typedef can all appear in one program
  • Which combinations are valid — and which are forbidden
  • How the compiler decides where each variable lives
  • Why you can't mix certain keywords (like static + extern on the same variable)
  • How to pick the right storage class for each variable

What Happens When You Mix Them?

Every variable in your program has a storage class. If you don't write one, the compiler picks a sensible default. Most of the time, mixing them just means each variable gets its own storage class in its own place — nothing more.

But some combinations are illegal. You can't have the same variable be both static and extern, or both auto and register. The compiler enforces these rules, so your job is simply to pick the right one per variable.

💡 In one line: Mixing storage classes is fine — just remember that each variable gets exactly one storage class. Different variables can use different ones.

C program combining auto, static, extern, register, and typedef in a single program

Simple Rules for Combining

Combination Allowed? Why
static + extern❌ NoContradictory — one means "file-only", the other means "shared"
auto + register❌ NoBoth are block-local; pick one
register + static❌ NoStatic needs an address; register forbids one
typedef + struct✅ YesCommonly combined for type aliases
static local + extern global in same file✅ YesDifferent variables — no conflict
register + auto implied✅ YesPlain register int i; is fine

Complete C Program

Program: All five storage classes in one file

#include <stdio.h>

/* ---------- typedef: give a struct a short name ---------- */
typedef struct {
    int x;
    int y;
} Point;

/* ---------- extern-style global: shared across the program ---------- */
int sharedTotal = 0;      /* defined once here */
extern int sharedTotal;   /* declared again - legal, same file */

/* ---------- helper functions ---------- */

void bumpStatic(void) {
    /* static local: lives for the whole program, private to this function */
    static int callCount = 0;
    callCount++;
    sharedTotal += callCount;
    printf("bumpStatic: callCount=%d, sharedTotal=%d\n",
           callCount, sharedTotal);
}

Point makePoint(int x, int y) {
    /* auto local: re-created each call, stack-allocated */
    Point p;
    p.x = x;
    p.y = y;
    return p;
}

int sumWithRegister(int n) {
    /* register hint: compiler may keep 'i' in a CPU register */
    register int i;
    int sum = 0;                 /* auto, by default */
    for (i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

int main(void) {
    int i;                       /* auto local */
    Point origin;

    printf("--- static + extern interaction ---\n");
    bumpStatic();
    bumpStatic();
    bumpStatic();

    printf("\n--- auto + typedef interaction ---\n");
    origin = makePoint(3, 4);
    printf("origin = (%d, %d)\n", origin.x, origin.y);

    printf("\n--- register + auto interaction ---\n");
    for (i = 1; i <= 3; i++) {
        printf("sumWithRegister(%d) = %d\n",
               i * 10, sumWithRegister(i * 10));
    }

    printf("\nFinal sharedTotal = %d\n", sharedTotal);
    return 0;
}
                                    

Program Output

--- static + extern interaction ---
bumpStatic: callCount=1, sharedTotal=1
bumpStatic: callCount=2, sharedTotal=3
bumpStatic: callCount=3, sharedTotal=6

--- auto + typedef interaction ---
origin = (3, 4)

--- register + auto interaction ---
sumWithRegister(10) = 55
sumWithRegister(20) = 210
sumWithRegister(30) = 465

Final sharedTotal = 6
                                

Step-by-Step Explanation

Let's walk through the program and see how each storage class behaves in its own context.

1. typedef — naming the struct:

typedef struct { int x; int y; } Point;
                                

This creates a type alias called Point. From here, Point p; works without needing the struct keyword.

2. extern-style global:

int sharedTotal = 0;
extern int sharedTotal;
                                

The first line defines the variable — this is where memory is allocated and it's initialized to 0. The second line declares it again with extern. Both refer to the same memory. (In a multi-file project, you'd put the extern declaration in a header file so other files can see it.)

3. static local — remembering its value:

void bumpStatic(void) {
    static int callCount = 0;
    callCount++;
    sharedTotal += callCount;
}
                                

On the first call, callCount is created with value 0, then goes to 1, and sharedTotal becomes 1. On the second call, callCount remembers its value (1), goes to 2, and sharedTotal becomes 1+2 = 3. Third call: callCount = 3, sharedTotal = 3+3 = 6. This is the classic static-counting pattern, interacting smoothly with an extern global.

4. auto local — the default in makePoint:

Point makePoint(int x, int y) {
    Point p;
    p.x = x;
    p.y = y;
    return p;
}
                                

p is an auto variable — created fresh on every call, destroyed when the function returns. The return p; copies the value back to the caller. This works because Point (from the typedef) is a value type — the copy is made before p goes out of scope.

5. register hint — the loop counter:

int sumWithRegister(int n) {
    register int i;
    int sum = 0;
    for (i = 1; i <= n; i++)
        sum += i;
    return sum;
}
                                

i is tagged register, hinting that the compiler should keep it in a CPU register. sum is a plain auto local. Both coexist without conflict — they're different variables. The compiler's optimizer would likely have put i in a register anyway.

6. How they interact in main:

int i;                 /* auto local */
Point origin;          /* using the typedef name */
                                

i is an auto variable in main. origin is a Point (thanks to typedef). When main calls bumpStatic, the static inside that function continues from where it left off. When it calls makePoint, a fresh auto p is created, used, and destroyed. Each function's storage class only affects its own variables.

🎯 Remember this: Storage classes are per variable, not per file. Mixing them freely is normal — just don't try to combine contradicting ones on the same variable (like static + extern, or register + static).

Frequently Asked Questions

1. Can I apply two storage classes to the same variable?

No — a variable gets exactly one storage class. The compiler will reject static extern int x;, register static int y;, and auto register int z; as invalid combinations.

2. Why does int x = 0; extern int x; work in the same file?

Because int x = 0; is a definition and extern int x; is a declaration. There's still only one variable, with one storage location. The second line just reasserts its existence.

3. Is register really compatible with modern compilers?

Yes — the compiler accepts it, but almost always ignores it. The optimizer decides on its own which variables live in registers. So register is legal, harmless, and mostly a no-op today. In C++17 it was removed entirely.

4. Can I put typedef in the same declaration as another storage class?

Yes, but they're independent. For example, typedef static int Count; would be strange but syntactically valid. In practice, typedefs are almost always written on their own line for clarity, and they never affect runtime.

5. What's the biggest risk of combining storage classes in one file?

Confusing yourself. A file that uses static, extern, and file-scope globals together can become hard to reason about — who can write this variable? When does its value reset? The safest pattern: keep state as local as possible, use static for per-function state, use extern only for genuinely shared data.

💡 Tip: Run nm on your compiled object file to see where each symbol lives — B for .bss (uninitialized globals), D for .data (initialized globals), T for .text (functions). It's the fastest way to build intuition about storage.

📖 Related Tutorials

  • Storage Classes in C — Full Tutorial
  • 1. auto Storage Class
  • 2. register Storage Class Performance
  • 3. static Storage Class State
  • 4. extern Storage Class Across Files
  • 5. typedef with Complex Data Type
  • All Storage Class Assignments

Previous Topic: -->> 5. typedef with Complex Data Type   ||   Next topic: -->> 7. Auto Variables in Recursion


C Language

  • Home
  • Why C Language
  • History of C Language
  • Applications of C Language
  • Introduction To C
    • What is Program?
    • Structure of C Program
    • Working Of C Program
    • CHARACTER SET
    • VARIABLES AND IDENTIFIERS
    • BUILT-IN DATA TYPES
    • OPERATORS AND EXPRESSIONS
    • CONSTANTS AND LITERALS
    • SIMPLE ASSIGNMENT STATEMENT
    • BASIC INPUT/OUTPUT STATEMENT
    • SIMPLE 'C' PROGRAMS
    • Assignments
  • Operators in C Programming
    • Arithmetic Operators
    • Assignment Operators
    • Increment and Decrement Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Other Operators
    • Assignments
  • CONDITIONAL STATEMENTS
    • DECISION MAKING WITHIN A PROGRAM
    • CONDITIONS
    • IF STATEMENT
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • SWITCH CASE
    • Assignments
  • LOOPS STATEMENTS
    • Introduction to Loops
    • GO TO Statement
    • Do while Loop
    • While Loop
    • Nested While Loop
    • Difference Between While and Do while
    • Difference Between Goto and loop
    • while loop assignments
    • C FOR Loop
    • C For loop examples
    • Nested for loop
    • Nested for loop examples
    • Infinite while Loops
    • Infinite for Loops
    • Continue in Loops
    • break in Loops
    • difference while do..while & for
    • Assignments
  • Arrays
    • One Dimensional Array
    • Declaring 1D Arrays
    • Initilization of 1D arrays
    • Accessing element of one 1D Array
    • Read and Display 1D Arrays
    • Two Dimensional Arrays
    • Declare 2D Arrays
    • Read and Display 2D Arrays
    • Assignments/Examples
  • Functions
    • Introduction
    • Need For User-Defined Function
    • Multiple Function Program
    • Modular Programming
    • Elements Of User Defined Function
    • Function Definition
    • Function Declaration
    • Types of functions
    • Nesting of Function
    • Recursion
    • Passing Array To Functions
    • Scope,Visibility and Lifetime of Variables
    • Assignments
  • Structure
    • Introduction
    • Array vs Structure
    • Defining Structure
    • Declaring Structure Variables
    • Type Defined Structure
    • Accessing Structure Members
    • Structure Initilization
    • Copying & Comparing Structure Variables
    • Array of Structure
    • Arrays Within Structure
    • Structures Within Structures
    • Structures and Functions
    • Structure Examples/Assignments
  • Union
    • Define Union
    • Create and use Union
    • Difference Between Structure and Union
    • Union Examples
    • Union FAQ
  • Pointers
    • What Are Pointers In C?
    • How Do We Use Pointers In C?
    • Declaration Of A Pointer
    • The Initialization Of A Pointer
    • Syntax Of Pointer Initialization
    • Use Of Pointers In C
    • The Pointer To An Array
    • The Pointer To A Function
    • The Pointer To A Structure
    • Types Of Pointers
    • The Null Pointer
    • The Void Pointer
    • The Wild Pointer
    • The Near Pointer
    • The Huge Pointer
    • The far Pointer
    • dangling pointer
    • Accessing Pointers- Indirectly And Directly
    • Pros Of Using Pointers In C
    • Cons Of Pointers In C
    • Applications Of Pointers In C
    • The & Address Of Operator In C
    • How To Read The Complex Pointers In C?
    • Practice Problems On Pointers
  • File Processiong
    • File Handling In C
    • Types Of Files In C
    • Operations Done In File Handling
    • File Examples
    • Binary Files
    • count words,lines in a file
    • Copy files
    • Update File
    • count vowels in a file
  • Preprocessor
    • Macro substitution division
    • File Inclusion
    • Conditional Compilation
    • Other directives
    • Examples
  • Dynamic Memory Allocation
    • malloc
    • calloc
    • free
    • realloc
    • Examples
  • Storage Classes
  • Graphics
  • Frequently Asked Interview Questions (FAQ)
    • Introduction To C FAQ
    • Operators FAQ
    • Conditional Statements FAQ
    • Loops FAQ
    • Arrays FAQ
    • Function FAQ
    • Structure FAQ
    • Pointers FAQ
    • Files FAQ
    • Storage classes FAQ
    • Dynamic Memory FAQ
  • Programs/Assignments
    • Introduction To C
    • Operators
    • Conditional Statements
    • Loops
    • Arrays
    • Function
    • Structure
    • Pointers
    • Files
    • Storage classes
    • Dynamic Memory
  • Case Studies
  • Multiple Choice Questions
    • Introduction To C MCQ
    • Operators MCQ
    • Conditional Statements MCQ
    • Loops MCQ
    • Arrays MCQ
    • Function MCQ
    • Structure MCQ
    • Pointers MCQ
    • Files MCQ
    • Storage classes MCQ
    • Dynamic Memory MCQ
    • More MCQ

Get in touch

  • tech2dsm@gmail.com

© Sankalan Data Tech. All rights reserved.