The conditional
(and the only ternary operator )
in
C (and Java)
expr1 ? expr2 : expr3
meaning:
First,
evaluate the expression expr1
If the result of
expr1 is
true (i.e., non-zero),
then
expr1 ? expr2 : expr3
will return the value
expr2
If the result of
expr1 is
false (i.e., equal to zero),
then
expr1 ? expr2 : expr3
will return the value
expr3
Example:
double x, y, z;
z = (x > y) ? x : y; // z will be assign with the larger value of x and y
Final note
The conditional operator is
also available in
Java.
It is oftenomitted
in introduction courses
to avoid causing confusion
at the introduction level.
The confusion can be
caused by using different types
of expressions in
expr2 and
expr3
Example:Java program
public class cond1
{
public static void main( String[] args )
{
int a = 4;
int c;
double x = 7.0; // Try: 5e30
System.out.printf("a = %d\n", a);
System.out.printf("x = %lf\n", x);
c = ( a > x ) ? a : x;
System.out.printf("c = %d\n", c);
}
}
This Java program
will not compile because:
cs255-1@aruba (4290)> javac cond1.java
cond1.java:17: error: incompatible types: possible lossy conversion from double to int
c = ( a > x ) ? a : x;
^
1 error
Explanation:
( a > x ) ? a : x can
return an int aor a
double x.
The result is assigned to an
int type variable
To cover all its bases, the Java compiler will
report a "incompatible type" error
(possibly assigning a
double value to
an int typed variable)
Fix:
c = ( a > x ) ? a : (int)x;
Postscript:
The expressionc = ( a > x ) ? a : x
will compile successfully in
C because:
C has more
flexibleautomatic conversion rule
that allow
C programmers to
assign a
double type to
an int type