SWITCH

Syntax | Examples | Version History | See Also

The SWITCH statement is used to select one statement for execution from multiple choices, depending upon the value of the expression following the word SWITCH.

Each statement that is part of a SWITCH statement is preceded by an expression that is compared to the value of the SWITCH expression. SWITCH executes by comparing the SWITCH expression with each selector expression in the order written. If a match is found, program execution jumps to that statement and execution continues from that point. Whereas CASE executes at most one statement within the CASE block, SWITCH executes the first matching statement and any following statements in the SWITCH block. Once a match is found in the SWITCH block, execution falls through to 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.

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

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=2

SWITCH x OF
1: PRINT, 'one'
2: PRINT, 'two'
3: PRINT, 'three'
4: PRINT, 'four'
ENDSWITCH
END

IDL Prints:

two 
three 
four 

Version History

5.4

Introduced

See Also

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