Please enable JavaScript to view this site.


Navigation: Macros > Macro Language > Instructions > Branching

Branching with the  SWITCH  Keyword

Scroll Prev Up Next More

The Switch-case-else-endswitch set of keywords allow you to specify that different sequences of instructions should be performed depending on the value of an integer or string expression.


The syntax is:


switch is followed, on the same line, by an integer or string expression.

A case block of instructions then follows, which is performed based on the value of the switch expression. Each case block finishes when it reaches either of the 3 keywords: else or endswitch, or another case statement.

If an else instruction is present, then the block of instructions between else and endswitch will be performed if none of the case statements correspond to the value of the switch value.

The else block is optional, but its absence can generate compilation warnings.


Below is an example of the syntax using an integer switch expression:

switch ((nToday() - nBirthDate) div 365// the age
   case 13..19
      sRESULT = 'teenager'
   case nLegalAge // you can use a variable <-
      sRESULT = 'allowed to drink'      
      sRESULT = 'too old to rock, too young to die'      

Below is an example of the syntax using a string switch expression:

switch sCityName
   case 'Paris'
      sRESULT = 'France'
   case 'London'
      sRESULT = 'United Kingdom'      
      sRESULT = 'The boondocks' // just kidding !      

Some important points to note:


You can use ranges of values in case statements.

You can use variables (not expressions) in the case statements.

The case values (or range of values) are tested in the order in which they appear, and only one case block is executed. So the first block which matches the switch value is executed and all other possible ones are ignored.


See also: branching with the if keyword.


Topic 115174, last updated on 18-Apr-2020