0
0
Cprogramming~5 mins

Extern storage class - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extern storage class
O(n)
Understanding Time Complexity

Let's explore how using the extern storage class affects the time complexity of a program.

We want to see how the program's running time changes when accessing variables declared with extern.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// file1.c
int count = 0;

void increment() {
    count++;
}

// file2.c
extern int count;

#include <stdio.h>

void printCount() {
    printf("Count: %d\n", count);
}
    

This code shows a variable declared in one file and accessed in another using extern.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Accessing and modifying the variable count.
  • How many times: Each time increment() or printCount() is called.
How Execution Grows With Input

Accessing an extern variable is a simple operation that does not depend on input size.

Input Size (n)Approx. Operations
1010 variable accesses
100100 variable accesses
10001000 variable accesses

Pattern observation: The number of operations grows directly with how many times the variable is accessed, but each access is constant time.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows linearly with the number of times the extern variable is accessed or modified.

Common Mistake

[X] Wrong: "Using extern makes variable access slower because it is declared outside the file."

[OK] Correct: Extern just tells the compiler the variable is defined elsewhere; accessing it is just like any other variable access and takes constant time.

Interview Connect

Understanding how extern variables behave helps you reason about program structure and performance, a useful skill in many coding situations.

Self-Check

"What if the extern variable was an array and we looped over it? How would the time complexity change?"