Fortran has one more selective execution statement, SELECT CASE, and could be very handy if it is used properly. The SELECT CASE statement is also usually referred to as the CASE statement. The following is its syntactic form:
where statements-1, statements-2, statements-3, ..., statements-n and statements-DEFAULT are sequences of executable statements, including the SELECT CASE statement itself, and selector is an expression whose result is of type INTEGER, CHARACTER or LOGICAL (i.e., no REAL type can be used for the selector). The label lists label-list-1, label-list-2, label-list-3, ..., and label-list-n are called case labels.SELECT CASE (selector) CASE (label-list-1) statements-1 CASE (label-list-2) statements-2 CASE (label-list-3) statements-3 ............. CASE (label-list-n) statements-n CASE DEFAULT statements-DEFAULT END SELECT
A label-list is a list of labels, separated by commas. Each label must be one of the following forms. In fact, three of these four are identical to an extent specifier for substrings:
where value, value-1 and value-2 are constants or alias defined by PARAMETER. The type of these constants must be identical to that of the selector.value value-1 : value-2 value-1 : : value-2
INTEGER :: Class SELECT CASE (Class) CASE (1) WRITE(*,*) 'Freshman' CASE (2) WRITE(*,*) 'Sophomore' CASE (3) WRITE(*,*) 'Junior' CASE (4) WRITE(*,*) 'Senior' CASE DEFAULT WRITE(*,*) "Hmmmm, I don't know" END SELECT WRITE(*,*) 'Done'
CHARACTER(LEN=4) :: Title INTEGER :: DrMD = 0, PhD = 0, MS = 0, BS = 0, Others = 0 SELECT CASE (Title) CASE ("DrMD") DrMD = DrMD + 1 CASE ("PhD") PhD = PhD + 1 CASE ("MS") MS = MS + 1 CASE ("BS") BS = BS + 1 CASE DEFAULT Others = Others + 1 END SELECT
INTEGER :: Number, Sign SELECT CASE (Number) CASE ( : -1) Sign = -1 CASE (0) Sign = 0 CASE (1 : ) Sign = 1 END SELECT WRITE(*,*) "Sign = ", Sign
CHARACTER(LEN=1) :: c SELECT CASE (c) CASE ('a' : 'j') WRITE(*,*) 'One of the first ten letters' CASE ('l' : 'p', 'u' : 'y') WRITE(*,*) 'One of l, m, n, o, p, u, v, w, x, y' CASE ('z', 'q' : 't') WRITE(*,*) 'One of z, q, r, s, t' CASE DEFAULT WRITE(*,*) 'Other characters, which may not be letters' END SELECT
Here is the result:INTEGER :: Number, Range SELECT CASE (Number) CASE ( : -10, 10 : ) Range = 1 CASE (-5:-3, 6:9) Range = 2 CASE (-2:2) Range = 3 CASE (3, 5) Range = 4 CASE (4) Range = 5 CASE DEFAULT Range = 6 END SELECT
Number | Range | Why? |
<= -10 | 1 | CASE ( : -10, 10 : ) |
-9, -8, -7, -6 | 6 | CASE DEFAULT |
-5, -4, -3 | 2 | CASE (-5:-3, 6:9) |
-2, -1, 0, 1, 2 | 3 | CASE (-2:2) |
3 | 4 | CASE (3, 5) |
4 | 5 | CASE (4) |
5 | 4 | CASE (3, 5) |
6, 7, 8, 9 | 2 | CASE (-5:-3, 6:9) | >= 10 | 1 | CASE ( : -10, 10 : ) |