Use Braces in Nested if Statements

It is legal to leave out the braces on if statements that are only a single statement, and it is legal to nest if statements, such as the following:

if (x > y)              // if x is bigger than y
    if (x < z)          // and if x is smaller than z
        x = y;          // then set x to the value in y

However, when you are writing large nested statements, this practice can cause enormous confusion. Remember, whitespace and indentation are a convenience for the programmer; they make no difference to the compiler. It is easy to confuse the logic and inadvertently assign an else statement to the wrong if statement. Listing 4.5 illustrates this problem.

Listing 4.5. Demonstrates Why Braces Help Clarify Which else Statement Goes with Which if Statement ...

Get Sams Teach Yourself C++ in 24 Hours, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.