O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required