Conditional compilation - Time & Space Complexity
Conditional compilation controls which parts of code run based on conditions.
We want to see how this affects the time the program takes to run.
Analyze the time complexity of the following code snippet.
#ifdef FEATURE_ENABLED
void feature() {
for (int i = 0; i < n; i++) {
process(i);
}
}
#endif
int main() {
#ifdef FEATURE_ENABLED
feature();
#endif
return 0;
}
This code runs a loop only if FEATURE_ENABLED is defined during compilation.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A for-loop running from 0 to n-1 inside the feature() function.
- How many times: The loop runs n times if FEATURE_ENABLED is defined; otherwise, it does not run at all.
The loop runs once for each item up to n, so more input means more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps if enabled, 0 if not |
| 100 | 100 loop steps if enabled, 0 if not |
| 1000 | 1000 loop steps if enabled, 0 if not |
Pattern observation: The work grows directly with n only when the feature is included; otherwise, it stays zero.
Time Complexity: O(n)
This means the program's running time grows in a straight line with the input size when the feature is included.
[X] Wrong: "Conditional compilation changes the time complexity regardless of what code is included."
[OK] Correct: Conditional compilation only includes or excludes code before running, so the time complexity depends on the code that actually runs, not on the condition itself.
Understanding how conditional compilation affects which code runs helps you explain performance clearly and shows you know how code structure impacts efficiency.
"What if the loop inside feature() called another function that itself had a loop over n? How would the time complexity change?"