1️⃣ The Idea: Counting How Many Times a Function Runs
Sometimes we want to track:
- How many times a function was called
- How many users logged in
- How many operations were performed
To do this, we need a variable that:
- Does not reset every time
- Stays in memory during the whole program
That’s where global and static variables help.
2️⃣ Using a Global Variable for Counting
#include <stdio.h>
int count = 0; // global variable
void test() {
count++;
printf("%d\\n", count);
}
int main() {
test();
test();
test();
}
Output:
1
2
3
Why it works:
count is global
- It stays in memory for the entire program
- Every function call increases the same variable
🔁 Alternative: Count Globally, Print Only Once