CASE

Syntax | Examples | Version History | See Also

The CASE statement selects one, and only one, statement for execution, depending on the value of an expression. This expression is called the case selector expression. 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.

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.

CASE is similar to the SWITCH statement. For more information on using CASE and other IDL program control statements, as well as the differences between CASE and SWITCH, see Program Control (Application Programming).

Syntax

CASE expression OF

    expression: statement

    ...

    expression: statement

[ ELSE: statement ]

ENDCASE

Examples

This example illustrates how the CASE statement, unlike SWITCH, executes only the one statement that matches the case expression:

x=2 
 
CASE x OF 
   1: PRINT, 'one' 
   2: PRINT, 'two' 
   3: PRINT, 'three' 
   4: PRINT, 'four' 
   ELSE: PRINT, 'Not one through four' 
ENDCASE 

IDL Prints:

two 

Version History

Original

Introduced

See Also

BEGIN...END, BREAK, CONTINUE, FOR, GOTO, IF...THEN...ELSE, REPEAT...UNTIL, SWITCH, WHILE...DO, Program Control (Application Programming)