Executes a block of code only if a given condition is true.
The if statement in C is used to test a condition. If the condition evaluates to true (non-zero), the code inside the block runs. Otherwise, it is skipped.
if (condition) {
// code to execute if condition is true
}If the condition in if is false, else will run.
Used to evaluate multiple conditions in order.
You can nest one if or else block inside another.
C uses integers for condition evaluation:
0 → falsenon-zero → true= instead of == in comparisonsFix: Use if (x == 10)
The switch statement compares a variable against several constant values. Each case should end in break to prevent fall-through.
When deciding between if and switch:
| if / else if | switch |
|---|---|
| Works with ranges and complex conditions | Only works with constant discrete values (e.g. int, char) |
| More flexible | More efficient for multiple exact matches |
Supports expressions like x > 5 | No support for expressions, just equality |
What will this print?
A. AB. BC. CAsk the AI if you need help understanding or want to dive deeper in any topic