7.3.8 Conditional Expressions

The statements

IF (a>b) THEN

LET m = a


LET m = b


compute in m the maximum of a and b. The conditional expression, written with the ternary operator '?', provides an alternative way to write this and similar constructions. In the expression


the expression <expression_if> is evaluated first. If it is true, then <expression_then> is evaluated, and that is the value of the conditional expression. Otherwise <expression_else> is evaluated, and that is the value. Only one of <expression_then> and <expression_else> is evaluated. According to the IF-THEN-ELSE statement above we can state the equivalent conditional statement

LET m = ?{(a>b),a,b}.

The conditional expression can be used to reduce code and to make programs more compact. A brief example should illustrate the use of CST(C&F)'s expression interpreters functionality.

LET c1 = MIN(i=1:10){Vector[i]}.

LET c2 = MAX{Array[j]}*#j.

LET result = ?{((c1>c2)|(c2=0)),(c1-c2),SQR(c1/c2)}

PRINT result

As we can see, this program works without any use of LOOP, FOR-NEXT or IF-THEN-ELSE-statements.