Conditional Expressions
A conditional expression is a primary expression. It selectively evaluates one chosen subexpression.
A conditional expression takes the following form:
| conditional-expr | is ( scalar-logical-expr ? expr [ : scalar-logical-expr ? expr ]. . . : expr ) |
Within a conditional expression, the rank, declared type, and kind type parameters of each expr must be the same.
When a conditional expression is evaluated, each scalar-logical-expr is evaluated from left to right until a scalar-logical-expr evaluates to .TRUE., or there are no more scalar-logical-exprs. When a scalar-logical-expr evaluates to .TRUE., the subsequent expr is evaluated, and its value becomes the value of conditional-expr. No subsequent scalar-logical-exprs are evaluated. If no scalar-logical-expr evaluates to .TRUE., the final expr is evaluated and its value becomes the value of conditional-expr.
Exactly one expr of conditional-expr is evaluated.
The rank, declared type, and kind type parameters of a conditional expression are the same as those of its exprs. The length type parameters, shape, and dynamic type of a conditional expression are those of the evaluated expr. if one or more exprs is polymorphic, the conditional expression is polymorphic.
The following are valid conditional expressions.
INTEGER(KIND=4) :: i = 3, j = 4, k
LOGICAL(KIND=1) :: l1 = .TRUE., l2 = .FALSE.
k = (l1 .AND. l2 ? i : j) ! k = 4
PRINT *, (l2 .or. l1 ? i, j) ! prints 3
The following shows a more complex conditional expression.
SUBROUTINE sub (a, b, c, d)
REAL(KIND=4) :: a, b, c, d
d = (b != 0.0 ? a/b : c != 0.0 ? a/c : a)
The assignment above could be equivalently written as:
IF (b /= 0.0) THEN
d = a/b
ELSE IF (c /= 0.0) THEN
d = a/c
ELSE
d = a
END IF
Conditional expressions may be nested. The scalar-logical-expr evaluation occurs left to right.
i = (j > k ? (j > m ? j : k > m ? k : m ) : -1)
The assignment above could be equivalently written as:
i = (j > k ? (j > m ? j : (k > m ? k : m)) : -1)
or as:
IF (j > k) THEN
IF (j > m) THEN
i = j
ELSE IF (k > m) THEN
i = k
ELSE
i = m
END IF
ELSE ! k <= m
i = -1
END IF