Difference between Global and Static Variables in C

1. Introduction

In the C programming language, variables can be categorized based on their scope and lifetime, particularly as global and static variables. A global variable is accessible from any function within the same program file, while a static variable's scope is limited to the function/block in which it is declared but its lifetime extends across the entire run of the program.

2. Key Points

1. Global variables are declared outside of all functions and are accessible from any function within the same file.

2. Static variables can be declared in functions or globally but maintain their values between function calls or throughout the program's life.

3. Global variables have a program-wide scope, while static variables have a local scope (if declared inside a function) or file scope (if declared outside of a function).

4. The lifetime of a global variable is throughout the program, similar to a static variable.

3. Differences

Global Variable Static Variable
Accessible from any function in the same file. Local scope when declared inside a function, but retains value between calls.
Has a program-wide scope. Has a local scope or file scope, but with a program-wide lifetime.
Lifetime is throughout the program. Lifetime is throughout the program but hidden from other functions if declared inside a function.

4. Example

#include <stdio.h>

int globalVar = 10; // Global variable

void function() {
    static int staticVar = 20; // Static variable
    printf("Inside function, staticVar: %d\n", staticVar);
    staticVar++;
}

int main() {
    printf("In main, globalVar: %d\n", globalVar);
    function();
    function();
    function();
    return 0;
}

Output:

In main, globalVar: 10
Inside function, staticVar: 20
Inside function, staticVar: 21
Inside function, staticVar: 22

Explanation:

1. globalVar is accessible in both main and function.

2. staticVar is only accessible within the function, but its value persists across multiple calls to the function.

5. When to use?

- Use global variables when you need to access the data from multiple functions across the same file.

- Use static variables within functions when you need to preserve the state between function calls, without making the variable accessible outside the function.

Comments