0
0
Cprogramming~5 mins

Lifetime and scope comparison - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lifetime and scope comparison
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Here, the loop runs a fixed 1000 times, so the work does not grow with input size.

Input Size (n)Approx. Operations
101000
1001000
10001000

Pattern observation: The number of operations stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the program does a fixed amount of work regardless of input size.

Common Mistake

[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.

Interview Connect

Understanding how variable lifetime and scope affect program behavior helps you explain code clearly and reason about performance in real projects.

Self-Check

"What if the loop count in func was based on a function parameter n? How would the time complexity change?"