File: gawk.info, Node: Switch Statement, Next: Break Statement, Prev: For Statement, Up: Statements 7.4.5 The 'switch' Statement ---------------------------- This minor node describes a 'gawk'-specific feature. If 'gawk' is in compatibility mode (*note Options::), it is not available. 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 (either regular, '/foo/', or strongly typed, '@/foo/') 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, the case statement bodies execute until a 'break', 'continue', 'next', 'nextfile', or 'exit' is encountered, or the end of the 'switch' statement itself. For example: while ((c = getopt(ARGC, ARGV, "aksx")) != -1) { switch (c) { case "a": # report size of all files all_files = TRUE; break case "k": BLOCK_SIZE = 1024 # 1K block size break case "s": # do sums only sum_only = TRUE break case "x": # don't cross filesystems fts_flags = or(fts_flags, FTS_XDEV) break case "?": default: usage() break } } Note that if none of the statements specified here halt execution of a matched 'case' statement, execution falls through to the next 'case' until execution halts. In this example, the 'case' for '"?"' falls through to the 'default' case, which is to call a function named 'usage()'. (The 'getopt()' function being called here is described in *note Getopt Function::.)