switch Statement

Action

Executes a particular statement depending on the value of an expression.

Syntax

switch (expr)
  case case-value(s)
    statements
  [case case-value(s)
    statements ]
  ...
  [default
    statements ]
Variable Description
expr An expression.
statements One or more statements.
case-value(s) One or more expressions, separated with commas. If the value of expr equals one of the case-values, control passes to the first statement in the case-values clause. See the Notes below.

Notes

  • A switch statement can take the place of a series of if statements. Your script evaluates expr once and compares this value to the value of each of the expressions in case-value(s). If the value equals one of the expressions, control passes to the statement that follows. Otherwise control transfers to the statement following the default label, if one exists. There can be only one default label, and it must be the last.

  • Although C requires a break statement in each case to explicitly transfer control out of the switch, 4Test does not require it. Once the last statement in the case has been executed, control automatically passes to the next statement after the switch statement.

Example

The following example illustrates all of the ways you can specify case-value(s).

[-] testcase switchExample ()
	[ ] INTEGER i 
	[-] for i = 1 to 12 
		[-] switch (i) 
			[-] case 1 // Compares i to 1
				[ ] Print (i, "Case 1")  
			[-] case 2, 4 // Compares i to 2 and 4 
				[ ] Print (i, "Case 2, 4")
			[-] case 5 to 7 // Compares i to 5, 6, and 7 
				[ ] Print (i, "Case 5 to 7") 
			[-] case 8 to 9, 11 to 12 // Compares i to 8,9,11,12
				[ ] Print (i, "Case 8 to 9 and 11 to 12") 
			[-] default // If i is none of the above 
				[ ] Print (i, "Default Case")
	[ ] 
	[ ] // This script prints:
	[ ] // 1 Case 1
	[ ] // 2 Case 2, 4
	[ ] // 3 Default Case
	[ ] // 4 Case 2, 4
	[ ] // 5 Case 5 to 7
	[ ] // 6 Case 5 to 7
	[ ] // 7 Case 5 to 7
	[ ] // 8 Case 8 to 9 and 11 to 12
	[ ] // 9 Case 8 to 9 and 11 to 12
	[ ] // 10 Default Case
	[ ] // 11 Case 8 to 9 and 11 to 12
	[ ] // 12 Case 8 to 9 and 11 to 12