Programming in C

(Barry) #1
The Conditional Operator 91

for ( d = 2; d < p; ++d )
if ( p % d == 0 )
isPrime = false;

if ( isPrime != false )
printf ("%i ", p);
}

printf ("\n");
return 0;
}


Program 6.10A Output


2 3 5 7 11 13 17 19 23 29 31 37 41 43 47


As you can see, by including <stdbool.h>in your program, you can declare variables to
be of type boolinstead of _Bool.This is strictly for cosmetic purposes because the for-
mer is easier to read and type than the latter, and it fits in more with the style of the
other basic C data types, such as int,float,and char.


The Conditional Operator


Perhaps the most unusual operator in the C language is one called the conditional opera-
tor. Unlike all other operators in C—which are either unary or binary operators—the
conditional operator is a ternaryoperator; that is, it takes three operands.The two sym-
bols that are used to denote this operator are the question mark (?) and the colon (:).
The first operand is placed before the ?,the second between the ?and the :, and the
third after the :.
The general format of the conditional operator is


condition? expression1 : expression2


where conditionis an expression, usually a relational expression, that is evaluated first
whenever the conditional operator is encountered. If the result of the evaluation of con-
ditionis TRUE (that is, nonzero), then expression1is evaluated and the result of the
evaluation becomes the result of the operation. If conditionevaluates FALSE (that is,
zero), then expression2is evaluated and its result becomes the result of the operation.
The conditional operator is most often used to assign one of two values to a variable
depending upon some condition. For example, suppose you have an integer variable x
and another integer variable s. If you want to assign –1to sif xwere less than zero, and
the value of x^2 to sotherwise, the following statement could be written:


s = ( x < 0 )? -1 : x * x;


Program 6.10A Continued
Free download pdf