Master decision making, loops, and machine-level execution. Learn how to direct the CPU's path through your code effectively.
The if statement executes code only if a condition is true. The else clause provides an alternative path.
Execute code only when condition is true.
Handle both true and false outcomes.
Shorthand for simple if-else assignment.
Multi-way branching optimization. More efficient than multiple if-else statements for fixed values.
Compilers optimize consecutive switch cases into a Jump Table. Instead of checking conditions sequentially (O(n)), the CPU uses the value to calculate the memory address of the code to run directly (O(1)).
break; statement causes execution to "fall through" to the next case automatically. Always check your breaks!
Repeating code blocks efficiently.
Best when iteration count is known.
Best for unknown iteration counts.
Guarantees execution at least once.
Altering the natural flow of execution.
goto label;, but it is considered bad practice as it creates "spaghetti code". It is typically only used for error handling cleanup in system programming.
How the CPU handles your decisions.
Modern CPUs use pipelines to execute instructions. A "branch" (if statement) breaks this pipeline because the CPU doesn't know which code to load next.
To fix this, CPUs guess the outcome (Branch Prediction). If guessed correctly, execution is instant. If wrong, the pipeline is flushed (performance penalty).