Programming in C

(Barry) #1

92 Chapter 6 Making Decisions


The condition x < 0is first tested when the preceding statement is executed.
Parentheses are generally placed around the condition expression to aid in the statement’s
readability.This is usually not required because the precedence of the conditional opera-
tor is very low—lower, in fact, than all other operators besides the assignment operators
and the comma operator.
If the value of xis less than zero, the expression immediately following the ?is evalu-
ated.This expression is simply the constant integer value –1, which is assigned to the
variable sif xis less than zero.
If the value of xis not less than zero, the expression immediately following the :is
evaluated and assigned to s. So if xis greater than or equal to zero, the value of x * x,
or x^2 , is assigned to s.
As another example of the use of the conditional operator, the following statement
assigns to the variable maxValuethe maximum of aand b:
maxValue = ( a > b )? a : b;
If the expression that is used after the :(the “else” part) consists of another conditional
operator, you can achieve the effects of an “else if ” clause. For example, the signfunction
that was implemented in Program 6.6 can be written in one program line using two
conditional operators as follows:
sign = ( number < 0 )? -1 : (( number == 0 )? 0 : 1);
If numberis less than zero,signis assigned the value –1; else if numberis equal to zero,
signis assigned the value 0 ; else it is assigned the value 1 .The parentheses around the
“else” part of the preceding expression are actually unnecessary.This is because the con-
ditional operator associates from right to left, meaning that multiple uses of this operator
in a single expression, such as in
e1? e2 : e3? e4 : e5
group from right to left and, therefore, are evaluated as
e1? e2 : ( e3? e4 : e5 )
It is not necessary that the conditional operator be used on the right-hand side of an
assignment—it can be used in any situation in which an expression could be used.This
means that you could display the sign of the variable number, without first assigning it to
a variable, using a printfstatement as shown:
printf ("Sign = %i\n", ( number < 0 )? –1 : ( number == 0 )? 0 : 1);
The conditional operator is very handy when writing preprocessor macrosin C.This is
seen in detail in Chapter 13, “The Preprocessor.”
This concludes the discussions on making decisions. In Chapter 7, “Working with
Arrays,” you get your first look at more sophisticated data types.The arrayis a powerful
concept that will find its way into many programs that you will develop in C. Before
moving on, test your understanding of the material covered in this chapter by complet-
ing the following exercises.
Free download pdf