Next: , Previous: For Statement, Up: Statements



6.4.5 The switch Statement

NOTE: This subsection describes an experimental feature added in gawk 3.1.3. It is not enabled by default. To enable it, use the --enable-switch option to configure when gawk is being configured and built. See Additional Configuration Options, for more information.

The switch statement allows the evaluation of an expression and the execution of statements based on a case match. Case statements are checked for a match in the order they are defined. If no suitable case is found, the default section is executed, if supplied.

Each case contains a single constant, be it numeric, string, or regexp. The switch expression is evaluated, and then each case's constant is compared against the result in turn. The type of constant determines the comparison: numeric or string do the usual comparisons. A regexp constant does a regular expression match against the string value of the original expression. The general form of the switch statement looks like this:

     switch (expression) {
     case value or regular expression:
         case-body
     default:
         default-body
     }

Control flow in the switch statement works as it does in C. Once a match to a given case is made, case statement bodies are executed until a break, continue, next, nextfile or exit is encountered, or the end of the switch statement itself. For example:

     switch (NR * 2 + 1) {
     case 3:
     case "11":
         print NR - 1
         break
     
     case /2[[:digit:]]+/:
         print NR
     
     default:
         print NR + 1
     
     case -1:
         print NR * -1
     }

Note that if none of the statements specified above halt execution of a matched case statement, execution falls through to the next case until execution halts. In the above example, for any case value starting with `2' followed by one or more digits, the print statement is executed and then falls through into the default section, executing its print statement. In turn, the −1 case will also be executed since the default does not halt execution.