CASE
The CASE statement is used to select one, and only one, statement for execution, depending upon the value of the expression following the word CASE. This expression is called the case selector expression. The general form of the CASE statement is as follows:
Each statement that is part of a CASE statement is preceded by an expression that is compared to the value of the selector expression. CASE executes by comparing the CASE expression with each selector expression in the order written. If a match is found, the statement is executed and control resumes directly below the CASE statement.
The ELSE clause of the CASE statement is optional. If included, it matches any selector expression, causing its code to be executed. For this reason, it is usually written as the last clause in the CASE statement. The ELSE statement is executed only if none of the preceding statement expressions match. If an ELSE clause is not included and none of the values match the selector, an error occurs and program execution stops.
The BREAK statement can be used within CASE statements to force an immediate exit from the CASE.
Example — Case Statement Use
An example of the CASE statement follows:
CASE name OF 'Larry': PRINT, 'Stooge 1' 'Moe': PRINT, 'Stooge 2' 'Curly': PRINT, 'Stooge 3' ELSE: PRINT, 'Not a Stooge' ENDCASE
Another example shows the CASE statement with the number 1 as the selector expression of the CASE. One is equivalent to true and is matched against each of the conditionals.
CASE 1 OF (X GT 0) AND (X LE 50): Y = 12 * X + 5 (X GT 50) AND (X LE 100): Y = 13 * X + 4 (X LE 200): BEGIN Y = 14 * X - 5 Z = X + Y END ELSE: PRINT, 'X has an illegal value.' ENDCASE
In this CASE statement, only one clause is selected, and that clause is the first one whose value is equal to the value of the case selector expression.
Tip
Each clause is tested in order, so it is most efficient to order the most frequently selected clauses first.