Scope of variables in C++ - Time & Space Complexity
We want to see how the time cost changes when we use variables in different places in code.
How does where a variable is declared affect how many times code runs?
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
int x = i * 2;
// do something with x
}
int y = 0;
for (int i = 0; i < n; i++) {
y += i;
}
This code shows two loops: one declares a variable inside the loop, the other outside.
Look at the loops and variable declarations that repeat.
- Primary operation: The for loops run n times each.
- How many times: Each loop runs exactly n times.
- Variable declarations: The variable inside the first loop is created and destroyed each time.
As n grows, the loops run more times, but variable scope does not add extra loops.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 loop steps (2 loops x 10 each) |
| 100 | About 200 loop steps |
| 1000 | About 2000 loop steps |
Pattern observation: The total steps grow linearly with n, regardless of where variables are declared.
Time Complexity: O(n)
This means the time grows in a straight line as the input size n grows.
[X] Wrong: "Declaring a variable inside a loop makes the code slower by adding extra loops."
[OK] Correct: Declaring a variable inside a loop does not add more loops; it only creates the variable each time, which is very fast and does not change the main time growth.
Understanding how variable scope affects performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we moved the variable declared inside the loop to outside the loop? How would the time complexity change?"