Please enable JavaScript to view this site.

DAQFactory User's Guide

Navigation: 5 Sequences & Scripting

5.13 Replacing multiple ifs with a switch statement

Scroll Prev Top Next More

If one you want to perform a different action for one of many possible options, you can use the switch/case/endswitch statements:

 

switch

  case (Input[0] > 5)

    Output = 2

  case (Input[0] > 3)

    Output = 1

  case (Input[0] > 1)

    Output = 0

  default

    Output = 5

endcase

This example sets Output to 2 if Input is greater than 5, to 1 if Input is greater than 3, but less than or equal to 5, to 0 if Input is greater than 1 but less than or equal to 3 and to 5 for any other value of Input.  The case statements execute in order.  Once a case statements expression evaluates to true, the steps following it until the next case or endcase are executed then the sequence jumps to the endcase statement.  Therefore only one case statement executes.  In this example, if Input[0] = 4 the second case Input[0] > 3 will be the first to evaluate to true so its steps will execute even though the third case, Input[0] > 1 is also true.  The default statement's steps execute if none of the other case statements evaluate to true.  The default statement is optional.  

The example above can also be written with if/else statements:

 

if (Input[0] > 5)

  Output = 2

else

  if (Input[0] > 3)

    Output = 1

  else

    if (Input[0] > 1)

      Output = 0

    else

      Output = 5

    endif

  endif

endif

As you can see, the case statement is a quite a bit clearer.