xHarbour Reference Documentation > Statement Reference xHarbour Developers Network  

SWITCH

Executes one or more blocks of statements.

Syntax

SWITCH <Expression>
  CASE <Constant1>
    <statements>
    [EXIT]
 [CASE <ConstantN>
    <statements>
    [EXIT] ]
 [DEFAULT
    <statements>]
END

Arguments

SWITCH <Expression>
The value of <Expression> must be of data type Character or Numeric. When it is of type Character, it must be a single character, not a character string. Numeric values must be integer values.
CASE <Constant1> .. <ConstantN>
<Constant> is a constant value of the same data type as <expression>. It must be a singlecharacter or an integer numeric value.

Description

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.

Info

See also:BEGIN SEQUENCE, DO CASE, FOR, FOR EACH, IF, TRY...CATCH
Category: Control structures , Statements , xHarbour extensions

Examples

// 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

Copyright © 2006-2007 xHarbour.com Inc. All rights reserved.
http://www.xHarbour.com
Created by docmaker.exe