Static storage class - Time & Space Complexity
Let's see how the static storage class affects the time complexity of a program.
We want to know if using static variables changes how long the program takes as input grows.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void countCalls() {
static int count = 0;
count++;
printf("Called %d times\n", count);
}
int main() {
for (int i = 0; i < 5; i++) {
countCalls();
}
return 0;
}
This code counts how many times the function countCalls is called using a static variable.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop inmaincallscountCallsrepeatedly. - How many times: The loop runs 5 times, so the function is called 5 times.
As the number of loop iterations grows, the function calls grow at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to countCalls |
| 100 | 100 calls to countCalls |
| 1000 | 1000 calls to countCalls |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times the function is called.
[X] Wrong: "Using a static variable makes the function run faster or slower depending on input size."
[OK] Correct: The static variable only keeps its value between calls; it does not change how many times the function runs or how long each call takes.
Understanding how static variables behave helps you explain function behavior clearly and shows you know how storage affects program flow.
"What if the static variable was replaced with a normal local variable? How would the time complexity change?"