Programming in C

(Barry) #1
The ifStatement 75

Nested ifStatements


In the general format of the ifstatement, remember that if the result of evaluating the
expression inside the parentheses is TRUE, the statement that immediately follows is
executed. It is perfectly valid that this program statement be another ifstatement, as in
the following statement:


if ( gameIsOver == 0 )
if ( playerToMove == YOU )
printf ("Your Move\n");


If the value of gameIsOveris 0 , the following statement is executed, which is another if
statement.This ifstatement compares the value of playerToMoveagainst YOU. If the two
values are equal, the message “Your Move” is displayed at the terminal.Therefore, the
printfstatement is executed only if gameIsOverequals 0 andplayerToMoveequals YOU.
In fact, this statement could have been equivalently formulated using compound rela-
tionals as follows:


if ( gameIsOver == 0 && playerToMove == YOU )
printf ("Your Move\n");


A more practical example of “nested”ifstatements is if you added an elseclause to the
previous example, as follows:


if ( gameIsOver == 0 )
if ( playerToMove == YOU )
printf ("Your Move\n");
else
printf ("My Move\n");


Execution of this statement proceeds as described previously. However, if gameIsOver
equals 0 and the value of playerToMoveis not equal to YOU,then the elseclause is exe-
cuted.This displays the message “My Move” at the terminal. If gameIsOverdoes not
equal 0 , the entire ifstatement that follows, including its associated elseclause, is
skipped.
Notice how the elseclause is associated with the ifstatement that tests the value of
playerToMove, and not with the ifstatement that tests the value of gameIsOver.The
general rule is that an elseclause is always associated with the last ifstatement that
does not contain an else.
You can go one step further and add an elseclause to the outermost ifstatement in
the preceding example.This elseclause is executed if the value of gameIsOveris not 0.


if ( gameIsOver == 0 )
if ( playerToMove == YOU )
printf ("Your Move\n");
else
printf ("My Move\n");
else
printf ("The game is over\n");

Free download pdf