Extern storage class - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Accessing and modifying the variable
count. - How many times: Each time
increment()orprintCount()is called.
Accessing an extern variable is a simple operation that does not depend on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 variable accesses |
| 100 | 100 variable accesses |
| 1000 | 1000 variable accesses |
Pattern observation: The number of operations grows directly with how many times the variable is accessed, but each access is constant time.
Time Complexity: O(n)
This means the total time grows linearly with the number of times the extern variable is accessed or modified.
[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.
Understanding how extern variables behave helps you reason about program structure and performance, a useful skill in many coding situations.
"What if the extern variable was an array and we looped over it? How would the time complexity change?"