Arbortext Command Language > Commands > switch
  
switch
switch (expression) { case constant1: statements break case constant2: statements break … default: statements break}
This command selects from a group of statements based on the value of the expression. The form of the statement is similar to that of the switch statement in the C programming language.
When the switch statement is executed, expression is evaluated and then control is transferred to the statement following the case whose constant value matches the expression. If the expression does not match a case value, control is transferred to the statement following the default prefix. If there is no default prefix, then control resumes following the end of the switch.
Case is a clause that delimits a set of alternative statements within a switch statement. The case and default prefixes do not alter flow of control. The break statement may be used to transfer control out of the switch statement.
The case constant may be a string value delimited by single or double quotes, or a regular expression delimited by slashes. For example, this:
switch (x) {
case 1:
message "x is 1"
break
case "one":
message "x is 'one'"
break
case /this|that/:
message "x contains 'this' or 'that'"
break
}
is equivalent to this:
if (x == 1) {
message "x is 1"
} else if (x == "one") {
message "x is 'one'"
} else if (match(x, "this|that")) {
message "x contains 'this' or 'that'"
}
Since the match function is used to evaluate a case prefix that specifies a regular expression, the statements following the case may use the match functions match_result, match_start, and match_length to extract parts of the matched expression.
If the case constants are all integer values or string constants of a single character, a jump table may be used to transfer control to the matched value. This executes considerably faster than a series of if,else if clauses. If the case values are all string values, a binary search is used (for more than three cases). A series of if,else if statements are compiled if the case values are regular expressions or are a mixture of string and integer value.
The body of the switch statement must be enclosed in braces. The case statements do not need to be enclosed in braces.
* 
The case constant label allows for variable substitution. For example:
readIncompete=-2
readError=-1
readEOF=0
switch (read(ch, buf, 512)) {
case $readIncomplete:
...
case $readError:
...
case $readEOF:
...
default:
...
}
Related Topics
break command
Using expressions