THE CONDITIONAL EXPRESSION OPERATOR
This conditional expression operator takes THREE operators. The
two symbols used to denote this operator are the ? and the :. The
first operand is placed before the ?, the second operand between
the ? and the :, and the third after the :. The general format
is,
condition ? expression1 : expression2
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the result of the evaluation becomes the result of the operation. If the condition is FALSE (zero), then expression2 is evaluated and its result becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x; If x is less than zero then s = -1 If x is greater than zero then s = x * x
Example program illustrating conditional expression operator
#include <stdio.h> main() { int input; printf("I will tell you if the number is positive, negative or zero!"\n"); printf("please enter your number now--->"); scanf("%d", &input ); (input < 0) ? printf("negative\n") : ((input > 0) ? printf("positive\n") : printf("zero\n")); } Sample Program Output I will tell you if the number is positive, negative or zero! please enter your number now---> 32 positive
CLASS EXERCISE C12
Evaluate the following expression, where a=4, b=5
least_value = ( a < b ) ? a : b;