C Program Using Global and Static Variables – Code Example and Explanation

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 TypeScopeLifetimeUse Case
GlobalEntire ProgramTill Program EndsShared configuration or counters
StaticLocal FunctionTill Program EndsPreserve 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.

Previous Article

Factorial Program in C Using Recursion – Simple Code with Explanation

Next Article

C Function to Convert Lowercase to Uppercase in a String – Simple Code Example

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨