Programming in C

(Barry) #1

76 Chapter 6 Making Decisions


The proper use of indentation goes a long way toward aiding your understanding of the
logic of complex statements.
Of course, even if you use indentation to indicate the way you think a statement will
be interpreted in the C language, it might not always coincide with the way that the
compiler actually interprets the statement. For instance, removing the first elseclause
from the previous example
if ( gameIsOver == 0 )
if ( playerToMove == YOU )
printf ("Your Move\n");
else
printf ("The game is over\n");
does notresult in the statement being interpreted as indicated by its format. Instead, this
statement is interpreted as
if ( gameIsOver == 0 )
if ( playerToMove == YOU )
printf ("Your Move\n");
else
printf ("The game is over\n");
because the elseclause is associated with the last un-elsed if.You can use braces to
force a different association in those cases in which an innermost ifdoes not contain an
else,but an outer ifdoes.The braces have the effect of “closing off ” the ifstatement.
Thus,
if ( gameIsOver == 0 ) {
if ( playerToMove == YOU )
printf ("Your Move\n");
}
else
printf ("The game is over\n");
achieves the desired effect, with the message “The game is over” being displayed if the
val ue of gameIsOveris not 0.

The else ifConstruct


You’ve seen how the elsestatement comes into play when you have a test against two
possible conditions—either the number is even, else it is odd; either the year is a leap
year, else it is not. However, programming decisions that you have to make are not
always so black-and-white. Consider the task of writing a program that displays –1if a
number typed in by a user is less than zero, 0 if the number typed in is equal to zero, and
1 if the number is greater than zero. (This is actually an implementation of what is com-
monly called the signfunction.) Obviously, you must make three tests in this case—to
determine if the number that is keyed in is negative, zero, or positive. Our simple if-
elseconstruct does not work. Of course, in this case, you could always resort to three
Free download pdf