The SWITCH statement selects a statement or block of statements for execution, depending on the value of an expression. This expression is called the "switch-selector" expression. Each statement that is part of a SWITCH statement is preceded by a "clause" expression that is compared to the value of the switch-selector expression. SWITCH executes by converting the clause expression to the data type of the switch-selector, and then comparing the two expressions. If a match is found, the statement is executed. Unlike CASE, IDL will then "fall through" and continue to execute any remaining statements. For this reason, the BREAK statement is commonly used within SWITCH statements to force an immediate exit from the SWITCH block.

The ELSE clause of the SWITCH 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 switch 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, program execution continues immediately below the SWITCH without executing any of the SWITCH statements.

For more information on the difference between CASE and SWITCH, see CASE Versus SWITCH.

Note: Before doing the comparison, IDL will automatically convert the clause expression to the data type of the switch-selector expression. This may lead to unexpected results if you try to compare strings to numbers, or floating-point values to integers.

Syntax


SWITCH expression OF

   expression: statement

   ...

   expression: statement

ELSE: statement

ENDSWITCH

Examples


This example illustrates how, unlike CASE, SWITCH executes the first matching statement and any following statements in the SWITCH block:

PRO ex_switch, x
   SWITCH x OF
      1: PRINT, 'one'
      2: PRINT, 'two'
      3: PRINT, 'three'
      4: BEGIN
         PRINT, 'four'
         BREAK
        END
      ELSE: BEGIN
         PRINT, 'You entered: ', x
         PRINT, 'Please enter a value between 1 and 4'
         END
   ENDSWITCH
END
ex_switch, 2

IDL Prints:

two
three
four

Version History


5.4

Introduced

See Also


BEGIN...END, BREAK, CASE, Case vs Switch, CONTINUE, FOR, FOREACH, GOTO, IF...THEN...ELSE, REPEAT...UNTIL, WHILE...DO

IDL Programming