The CASE construct conditionally executes one block of constructs or statements depending on the value of a scalar expression in a SELECT CASE statement.
The CASE construct takes the following form:
Integer and character expressions can be expressed as a range of case values, taking one of the following forms:
low:high
low:
:high
Case values must not overlap.
If a construct name is specified in a SELECT CASE statement, the same name must appear in the corresponding END SELECT statement. The same construct name can optionally appear in any CASE statement in the construct. The same construct name must not be used for different named constructs in the same scoping unit.
The case expression (expr) is evaluated first. The resulting case index is compared to the case values to find a matching value (there can only be one). When a match occurs, the block following the matching case value is executed and the construct terminates.
The following rules determine whether a match occurs:
Data Type | A Match Occurs If: |
---|---|
Logical | case-index .EQV. case- value |
Integer or Character | case-index = = case-value |
Range | A Match Occurs If: |
---|---|
low: | case-index >= low |
:high | case-index <= high |
low:high | low <= case-index <= high |
The following are all valid case values:
CASE (1, 4, 7, 11:14, 22) ! Individual values as specified:
! 1, 4, 7, 11, 12, 13, 14, 22
CASE (:-1) ! All values less than zero
CASE (0) ! Only zero
CASE (1:) ! All values above zero
If no match occurs but a CASE DEFAULT statement is present, the block following that statement is executed and the construct terminates.
If no match occurs and no CASE DEFAULT statement is present, no block is executed, the construct terminates, and control passes to the next executable statement or construct following the END SELECT statement.
Figure 7-1 shows the flow of control in a CASE construct.
Figure 7-1 Flow of Control in CASE Constructs
You cannot use branching statements to transfer control to a CASE statement. However, branching to a SELECT CASE statement is allowed. Branching to the END SELECT statement is allowed only from within the CASE construct.
Examples
The following are examples of CASE constructs:
INTEGER FUNCTION STATUS_CODE (I)
INTEGER I
CHECK_STATUS: SELECT CASE (I)
CASE (:-1)
STATUS_CODE = -1
CASE (0)
STATUS_CODE = 0
CASE (1:)
STATUS_CODE = 1
END SELECT CHECK_STATUS
END FUNCTION STATUS_CODE
SELECT CASE (J)
CASE (1, 3:7, 9) ! Values: 1, 3, 4, 5, 6, 7, 9
CALL SUB_A
CASE DEFAULT
CALL SUB_B
END SELECT
The following three examples are equivalent:
1. SELECT CASE (ITEST .EQ. 1)
CASE (.TRUE.)
CALL SUB1 ()
CASE (.FALSE.)
CALL SUB2 ()
END SELECT
2. SELECT CASE (ITEST)
CASE DEFAULT
CALL SUB2 ()
CASE (1)
CALL SUB1 ()
END SELECT
3. IF (ITEST .EQ. 1) THEN
CALL SUB1 ()
ELSE
CALL SUB2 ()
END IF