Ch3.3: if-else
The if-else Statement
An if chooses whether to run a statement.
An if-else chooses between two statements:
if (cond) {
;
} else {
;
}
As before, ; is just an empty statement.
else if
For more than two cases, you can chain conditions using else if:
if (x < 0) {
print("negative\n");
} else if (x == 0) {
print("zero\n");
} else {
print("positive\n");
}
Only the first matching branch runs.
Init-statement
An if or else if may declare a variable before the condition.
C++ allows two different ways to write this.
The variable exists only inside the entire if / else if / else chain.
Form 1
::std::uint_least32_t a{3};
::std::uint_least32_t b{9};
if (::std::int_least32_t sum = a + b) { // condition is: sum != 0
println("sum != 0, a=", a, ", b=", b, ", sum=", sum);
} else {
println("sum == 0, a=", a, ", b=", b, ", sum=", sum);
}
In this form, the condition is simply whether the variable is nonzero.
Form 2
if (auto sum = a + b; sum > 10) {
println("sum > 10, a=", a, ", b=", b, ", sum=", sum);
} else if (sum == 10) {
println("sum == 10, a=", a, ", b=", b, ", sum=", sum);
} else {
println("sum < 10, a=", a, ", b=", b, ", sum=", sum);
}
In this form, the variable is declared first, and then a separate condition is checked.
In both forms, the variable (sum) is destroyed after the whole chain ends.
Always Use { }
Beginners should always use braces for if, else if, and else.
Without braces, it is extremely easy to attach the else to the wrong if.
❌ Wrong (ambiguous)
if (a)
if (b)
;
else
; // attaches to the inner if, not the outer one
This is the classic “dangling else” problem.
✔️ Correct
if (a) {
if (b) {
;
} else {
;
}
}
Braces make the structure clear and prevent mistakes.
Another Confusing Example
Without braces, this code looks like the else belongs to the first if:
❌ Wrong
if (x > 0)
if (x == 1)
print("one\n");
else
print("not one\n"); // actually belongs to the inner if
But the else always pairs with the nearest unmatched if.
✔️ Correct
if (x > 0) {
if (x == 1) {
print("one\n");
} else {
print("not one\n");
}
}
Always use braces. It removes all ambiguity.
Key takeaways
- if-else chooses:
ifpicks one path;if-elsepicks between two. - else if chains: use
else iffor multiple ordered conditions. - Init-statement: both forms of
if (init) ...andif (init; cond)declare a variable valid for the entire chain. - Single-statement rule: without braces, each branch controls only one statement.
- Empty statement:
if (cond) ;orelse ;does nothing and is almost always a bug. - Dangling else:
elsebinds to the nearestif; braces prevent confusion. - Clarity: consistent braces make code easier to read and safer to modify.