Why storage classes are needed - Performance Analysis
We want to see how the use of storage classes affects the time it takes for a program to run.
Specifically, we ask: does choosing different storage classes change how fast the program runs as input grows?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void countUp(int n) {
static int counter = 0;
for (int i = 0; i < n; i++) {
counter++;
}
printf("Counter: %d\n", counter);
}
int main() {
countUp(5);
countUp(3);
return 0;
}
This code uses a static storage class variable inside a function to keep track of a count across calls.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs from 0 to n-1.
- How many times: Exactly n times each call to countUp.
As n grows, the number of loop steps grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to run grows directly with the size of the input n.
[X] Wrong: "Using static variables makes the loop run faster because the variable keeps its value."
[OK] Correct: The static variable only keeps its value between calls; it does not reduce the number of loop steps. The loop still runs n times each call.
Understanding how storage classes affect program behavior helps you explain how variables live and change over time, which is a key skill in writing efficient and clear code.
"What if we changed the static variable to a regular local variable? How would the time complexity change?"