Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Static and Extern Storage Classes

In C, storage classes define the scope (visibility) and lifetime of variables. Two important storage classes are static and extern. Here’s an explanation of each, along with examples:

1. static

The static storage class is used to declare variables that maintain their value between function calls. When a variable is declared as static, its lifetime extends to the duration of the program, but its scope is limited to the block in which it is declared. This means that the variable retains its value even after the function has finished executing.

Example of static

#include <stdio.h>

void increment() {
    static int count = 0;  // Static variable
    count++;                // Incrementing the static variable
    printf("Count: %d\n", count);
}

int main() {
    increment();  // Output: Count: 1
    increment();  // Output: Count: 2
    increment();  // Output: Count: 3
    return 0;
}

Explanation:

  • In this example, the count variable is declared as static within the increment function.
  • Each time increment is called, count retains its value from the previous call, so it increments correctly.
  • If count were a regular local variable, it would be reinitialized to 0 every time the function is called.

2. extern

The extern storage class is used to declare a variable that is defined in another file or scope. It allows access to global variables from other files. When a variable is declared as extern, it does not allocate storage; it merely informs the compiler that the variable is defined elsewhere.

Example of extern

File 1: file1.c

#include <stdio.h>

int globalVar = 10;  // Global variable

void display() {
    printf("Global Variable: %d\n", globalVar);
}

File 2: file2.c

#include <stdio.h>

extern int globalVar;  // Declaration of the external variable

void modify() {
    globalVar += 5;  // Modifying the external variable
}

int main() {
    display();       // Output: Global Variable: 10
    modify();
    display();       // Output: Global Variable: 15
    return 0;
}

Explanation:

  • In file1.c, globalVar is defined as a global variable.
  • In file2.c, extern int globalVar; declares that globalVar is defined elsewhere (in this case, in file1.c).
  • The modify function modifies the value of globalVar.
  • When display is called in main, it shows the updated value after calling modify.

Summary

  • static:
    • Scope: Limited to the block in which it is declared.
    • Lifetime: The variable retains its value between function calls and lasts until the program ends.
  • extern:
    • Scope: Accessible across multiple files.
    • Lifetime: The variable is defined elsewhere, allowing other files to use it without redefining it.

    Leave a Reply

    Your email address will not be published.

    Need Help?