0
0
Cprogramming~5 mins

Static storage class - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Static storage class
O(n)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop in main calls countCalls repeatedly.
  • How many times: The loop runs 5 times, so the function is called 5 times.
How Execution Grows With Input

As the number of loop iterations grows, the function calls grow at the same rate.

Input Size (n)Approx. Operations
1010 calls to countCalls
100100 calls to countCalls
10001000 calls to countCalls

Pattern observation: The number of operations grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of times the function is called.

Common Mistake

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

Interview Connect

Understanding how static variables behave helps you explain function behavior clearly and shows you know how storage affects program flow.

Self-Check

"What if the static variable was replaced with a normal local variable? How would the time complexity change?"