SWITCH function

Purpose

Return one of a series of values based upon a TRUE/FALSE evaluation of a corresponding series of expressions.

Syntax

var  = SWITCH(expr1, val1 [[, expr2, val2], ...])

var& = SWITCH&(expr1, val1& [[, expr2, val2&], ...])

var$ = SWITCH$(expr1, val1$ [[, expr2, val2$], ...])

Remarks

SWITCH expects values of any numeric type.  SWITCH& expects values optimized for Long-integer type.  SWITCH$ expects values of string type.

If expr1 evaluates TRUE, val1 is returned, if expr2 evaluates TRUE, val2 is returned, etc.

Each control expression in the series is evaluated as a typical PowerBASIC Boolean expression, which offers short-circuit expression evaluation as needed.  To force a bitwise evaluation of an expression, enclose it in parentheses.  The value parameters may be expressions, literals or variables of the appropriate data type for the SWITCH function in use.

SWITCH returns the matching value parameter from the first TRUE evaluation of the control expressions, evaluated from left to right in the list.  Therefore, it would be wise to place the most likely selections at the front of the SWITCH list to achieve the utmost efficiency.  If no expressions evaluate to TRUE, then zero (0) is returned.

Restrictions

Contrary to the implementation in some other languages, only the chosen value (one of val1, val2, val3…) is evaluated at run-time; the other value parameters are not.  This ensures optimum execution speed, as well as the elimination of unanticipated side effects.

See also

CHOOSE, IF, IIF, SELECT

Example

' SWITCH with simple expressions

A$ = SWITCH$(x%=1, "Bob", x%=20, "Bruce", x% > 20, "Dan", x% < 1, "Nobody!")

 

' SWITCH with complex expressions

FUNCTION z(i&) AS LONG

  INCR i&

  FUNCTION = i&

END FUNCTION

 

FUNCTION PBMAIN

  x& = -1

  Choice& = SWITCH&(z(x&), 1, z(x&), 2, z(x&), 3)

  ' Choice& will equal 2

END FUNCTION