Goto statement overview in C - Time & Space Complexity
Let's see how using the goto statement affects how long a program takes to run.
We want to know if jumping around with goto changes the work done as input grows.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
int i = 0;
start:
if (i >= 5) goto end;
printf("%d\n", i);
i++;
goto start;
end:
return 0;
}
This code prints numbers from 0 to 4 using goto to loop instead of a normal loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The repeated printing and incrementing controlled by goto.
- How many times: The code jumps back and repeats 5 times before stopping.
Each time the input limit increases, the number of jumps and prints grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 5 jumps and prints |
| 10 | 10 jumps and prints |
| 100 | 100 jumps and prints |
Pattern observation: The work grows directly with the input size, one step per input.
Time Complexity: O(n)
This means the program takes longer in a straight line as the input number grows.
[X] Wrong: "Using goto makes the program faster or slower in a big way."
[OK] Correct: Goto just changes how the code jumps but does not change how many times the main work happens.
Understanding how goto affects time helps you see that structure changes don't always change work done.
"What if we replaced the goto with a for loop? How would the time complexity change?"