Sams Teach Yourself C++ in 21 Days

(singke) #1
Creating Expressions and Statements 83

4


Note that if the initial Yankees’ score is higher than the Mets score, the ifstatement on
line 18 evaluates as false, and line 19 is not invoked. The test on line 21 evaluates as
true, and the statement on line 23 is invoked. Then, the ifstatement on line 26 is tested
and this is false(if line 18 is true). Thus, the program skips the entire block, falling
through to line 41.


This example illustrates that getting a true result in one ifstatement does not stop other
ifstatements from being tested.


Note that the action for the first two ifstatements is one line (printing “Let’s Go Mets!”
or “Go Yankees!”). In the first example (on line 19), this line is not in braces; a single line
block doesn’t need them. The braces are legal, however, and are used on lines 22–24.


Avoiding Common Errors with ifStatements
Many novice C++ programmers inadvertently put a semicolon after their ifstatements:
if(SomeValue < 10); // Oops! Notice the semicolon!
SomeValue = 10;
What was intended here was to test whether SomeValueis less than 10, and if so, to set it
to 10 , making 10 the minimum value for SomeValue. Running this code snippet shows that
SomeValueis always set to 10! Why? The ifstatement terminates with the semicolon (the
do-nothing operator).
Remember that indentation has no meaning to the compiler. This snippet could more
accurately have been written as
if (SomeValue < 10) // test
; // do nothing
SomeValue = 10; // assign
Removing the semicolon makes the final line part of the ifstatement and makes this
code do what was intended.
To minimize the chances of this problem, you can always write your ifstatements with
braces, even when the body of the ifstatement is only one line:
if (SomeValue < 10)
{
SomeValue = 10;
};

Indentation Styles ............................................................................................


Listing 4.4 shows one style of indenting ifstatements. Nothing is more likely to create a
religious war, however, than to ask a group of programmers what is the best style for
brace alignment. Although dozens of variations are possible, the following appear to be
the most popular three:

Free download pdf