Sams Teach Yourself C++ in 21 Days

(singke) #1

Advanced ifStatements ..................................................................................


It is worth noting that any statement can be used in an ifor elseclause, even another if
or elsestatement. Thus, you might see complex ifstatements in the following form:
if (expression1)
{
if (expression2)
statement1;
else
{
if (expression3)
statement2;
else
statement3;
}
}
else
statement4;
This cumbersome ifstatement says, “If expression1is true and expression2is true,
execute statement1. If expression1is true but expression2is not true, then if expres-
sion3is true execute statement2. If expression1is true but expression2and expres-
sion3are false, then execute statement3. Finally, if expression1is not true, execute
statement4.” As you can see, complex ifstatements can be confusing!
Listing 4.6 gives an example of one such complex ifstatement.

86 Day 4


Form 2
if (expression)
statement1;
else
statement2;
next_statement;
If the expressionevaluates true, statement1is executed; otherwise, statement2is exe-
cuted. Afterward, the program continues with the next_statement.
Example 1
Example
if (SomeValue < 10)
cout << “SomeValue is less than 10”);
else
cout << “SomeValue is not less than 10!”);
cout << “Done.” << endl;
Free download pdf