Sams Teach Yourself C++ in 21 Days

(singke) #1
14: std::cout << “More than 100, Thanks!\n”;
15: }
16: else // fixed!
17: std::cout << “Less than 10, Thanks!\n”;
18: return 0;
19: }

Enter a number less than 10 or greater than 100: 9
Less than 10, Thanks!
The braces on lines 12 and 15 make everything between them into one statement,
and now the elseon line 16 applies to the ifon line 11, as intended.
If the user types 9, the ifstatement on line 11 is true; however, the ifstatement on line
13 is false, so nothing would be printed. It would be better if the programmer put another
elseclause after line 14 so that errors would be caught and a message printed.

OUTPUT


90 Day 4


LISTING4.8 continued

ANALYSIS

You can minimize many of the problems that come with if...elsestate-
ments by always using braces for the statements in the ifand elseclauses,
even when only one statement follows the condition.
if (SomeValue < 10)
{
SomeValue = 10;
}
else
{
SomeValue = 25;
};

TIP

The programs shown in this book are written to demonstrate the particular
issues being discussed. They are kept intentionally simple; no attempt is
made to “bulletproof” the code to protect against user error. Ideally, in
professional-quality code, every possible user error is anticipated and han-
dled gracefully.

NOTE
Free download pdf