xHarbour Reference Documentation > Statement Reference |
Executes one or more blocks of statements.
SWITCH <Expression> CASE <Constant1> <statements> [EXIT] [CASE <ConstantN> <statements> [EXIT] ] [DEFAULT <statements>] END
The SWITCH statement compares a constant value against a series of constant values. It is similar to the DO CASE statement but outperforms it to a great extent due to the restrictions introduced with values permitted for comparison. As a general rule, only literal values in form of single characters or integer constants may follow the CASE clauses.
The SWITCH statement evaluates <Expression> and then searches for a first match between the resulting value and <Constant>. When a match is found, the statements following the corresponding CASE clause are executed down to the END statement. To suppress execution of statements of the next CASE clause, the EXIT statement must be explicitely used. This is a major difference to the DO CASE statement where subsequent CASE clauses are skipped once a first match is found.
If no initial match is found with the CASE clauses, the statements following DEFAULT are executed, if present.
See also: | BEGIN SEQUENCE, DO CASE, FOR, FOR EACH, IF, TRY...CATCH |
Category: | Control structures , Statements , xHarbour extensions |
// The example demonstrates the SWITCH control structure with // EXIT statement PROCEDURE Main LOCAL nMonth := Month( Date() ) SWITCH nMonth CASE 1 CASE 2 CASE 3 ? "First Quarter" EXIT CASE 4 CASE 5 CASE 6 ? "Second Quarter" EXIT CASE 7 CASE 8 CASE 9 ? "Third Quarter" EXIT DEFAULT ? "Fourth quarter" END RETURN
// The example demonstrates the SWITCH control structure without // EXIT statement PROCEDURE Main LOCAL x := "D" SWITCH x CASE "A" ? "A" CASE "B" ? "B" CASE "D" ? "DEF" CASE "H" ? "HIJ" DEFAULT ? "Default" END RETURN ** Output: // DEF // HIJ // Default
http://www.xHarbour.com