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:
[name :] SELECT CASE (expr) [CASE (case-value [,case-value] . . . ) [name] block] . . . [CASE DEFAULT [name] block] END SELECT [name]
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 program unit; it must be unique.
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 .GE. low |
:high | case-index .LE. high |
low:high | low .LE. case-index .LE. high |
The following are all valid case values:
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 5-1 shows the flow of control in
a CASE construct.
You cannot transfer control to a CASE statement, but you can
transfer control to a SELECT CASE statement. You can transfer to
the END SELECT statement only from within the CASE construct.
The following are examples of CASE constructs:
The following three examples are equivalent:
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
Figure 5-1 Flow of Control in CASE Constructs
(Alpha only)
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
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