Lifetime and scope comparison - Time & Space Complexity
When we look at lifetime and scope in C, we want to understand how long variables exist and where they can be used.
We ask: How does the program's work change as we use variables with different lifetimes and scopes?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void func() {
int x = 0; // local variable
for (int i = 0; i < 1000; i++) {
x += i;
}
printf("%d\n", x);
}
int main() {
static int y = 0; // static variable
y++;
func();
return 0;
}
This code shows a local variable inside a function and a static variable in main, then runs a loop inside func.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside func that runs 1000 times.
- How many times: Exactly 1000 times each time func is called.
Here, the loop runs a fixed 1000 times, so the work does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1000 |
| 100 | 1000 |
| 1000 | 1000 |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program does a fixed amount of work regardless of input size.
[X] Wrong: "Because there is a loop, the time complexity must grow with input size."
[OK] Correct: The loop runs a fixed number of times (1000), so it does not depend on input size and stays constant.
Understanding how variable lifetime and scope affect program behavior helps you explain code clearly and reason about performance in real projects.
"What if the loop count in func was based on a function parameter n? How would the time complexity change?"