Understanding the difference between global and static variables is important when learning C programming. In this blog post, we’ll cover how to write a C program using global and static variables, with a clear explanation and code example.
What Are Global and Static Variables in C?
Global Variable:
A global variable is declared outside of all functions, including main()
. It is accessible from any function within the program.
Static Variable:
A static variable retains its value between multiple function calls. It is declared using the static
keyword inside a function.
Example: C Program Using Global and Static Variables
#include <stdio.h>
// Global variable
int globalCounter = 0;
void increment() {
// Static variable
static int staticCounter = 0;
globalCounter++;
staticCounter++;
printf("Global Counter: %d, Static Counter: %d\n", globalCounter, staticCounter);
}
int main() {
printf("Calling increment() three times:\n");
increment();
increment();
increment();
return 0;
}
Output:
Calling increment() three times:
Global Counter: 1, Static Counter: 1
Global Counter: 2, Static Counter: 2
Global Counter: 3, Static Counter: 3
Explanation:
globalCounter
is shared across the entire program and increases with each call.staticCounter
retains its value even after the function exits, maintaining its state across calls.
When to Use Global and Static Variables?
Variable Type | Scope | Lifetime | Use Case |
---|---|---|---|
Global | Entire Program | Till Program Ends | Shared configuration or counters |
Static | Local Function | Till Program Ends | Preserve function state (caching, etc.) |
Final Thoughts
Using global and static variables in C helps manage data scope and persistence efficiently. Understanding their behavior is essential for writing optimized and well-structured C programs.
Practice this example and observe how variable scope and lifetime affect program behavior.