Write a c program to illustrate the use of storage classes.

 #include <stdio.h>


// Global variable (external storage class)

int globalVar = 100;


// Static global variable (file scope only)

static int staticGlobalVar = 200;


// Function to demonstrate auto storage class

void autoDemo() {

    auto int autoVar = 10;  // 'auto' keyword is optional

    printf("\n--- AUTO Storage Class ---\n");

    printf("Auto variable: %d\n", autoVar);

    autoVar++;

    printf("After increment: %d\n", autoVar);

}


// Function to demonstrate static storage class

void staticDemo() {

    static int staticVar = 0;  // Initialized only once

    int normalVar = 0;

    

    printf("\n--- STATIC Storage Class ---\n");

    staticVar++;

    normalVar++;

    printf("Static variable: %d\n", staticVar);

    printf("Normal variable: %d\n", normalVar);

}


// Function to demonstrate register storage class

void registerDemo() {

    register int i;  // Hint to store in CPU register

    int sum = 0;

    

    printf("\n--- REGISTER Storage Class ---\n");

    for (i = 1; i <= 5; i++) {

        sum += i;

    }

    printf("Sum using register variable: %d\n", sum);

    // Note: Cannot use &i (address operator) with register variables

}


// Function to demonstrate extern storage class

void externDemo() {

    extern int globalVar;  // Declaration of external variable

    

    printf("\n--- EXTERN Storage Class ---\n");

    printf("Global variable (extern): %d\n", globalVar);

    globalVar += 50;

    printf("After modification: %d\n", globalVar);

}


int main() {

    printf("========== STORAGE CLASSES DEMONSTRATION ==========\n");

    

    // 1. Auto storage class

    autoDemo();

    autoDemo();  // autoVar resets each time

    

    // 2. Static storage class

    staticDemo();

    staticDemo();  // staticVar retains its value

    staticDemo();

    

    // 3. Register storage class

    registerDemo();

    

    // 4. Extern storage class

    externDemo();

    printf("Global variable in main: %d\n", globalVar);

    

    // 5. Static global variable

    printf("\n--- STATIC GLOBAL Variable ---\n");

    printf("Static global variable: %d\n", staticGlobalVar);

    

    printf("\n========== SUMMARY ==========\n");

    printf("AUTO: Default, local scope, automatic lifetime\n");

    printf("STATIC: Retains value between calls, local/global scope\n");

    printf("REGISTER: Stored in CPU register for faster access\n");

    printf("EXTERN: Declares global variables from other files\n");

    

    return 0;

}




Comments