We’re here to help you

Menu

Using Guards

Guards are boolean expressions based on variables. The statement behind the guard is selected if the expression evaluates to true. If more than one guard evaluates to true, a non-deterministic choice for one of guards must be made. Guards can be nested.

Syntax

An expression between [ and ] is used to declare a guarded statement

[expression] statement;

Here the statement will only be executed when expression evaluates to true.

Expression can be a compound expression using the logic operators || (OR) and &&(AND):

[expression1 || expression2] statement;  // statement will be executed when expression1 or expression2 is true
[expression1 && expression2] statement;  // statement will be executed when exrpession1 and expression2 is true

The keyword 'otherwise' defines a catch-all guard which is true only when none of the other guard expressions in a list of guarded statements evaluates to true.

[expression1] statement-true-1;
[expression2] statement-true-2;
[otherwise]   statement-false-1-2;

Here statement-true-1 will be executed when expression1 evaluates to true, statement-true-2 will be executed when expression2 evaluates to true and statement-false-1-2 will be executed when both expression1 and expression2 evaluate to false.

Examples

Simple state machine

This example shows a simple state machine for a siren where guards are used to select the correct actions based on the state.

interface Siren
{
  in void TurnOn();
  in void TurnOff();

  behaviour
  {
    enum State { SirenOff, SirenOn }; // type declaration
    State state = State.SirenOff;    // variable declaration

    [state.SirenOff] // if the Siren is off, only allow to turn it on
    {
      on TurnOn:  state = State.SirenOn;
      on TurnOff: illegal;
    }
    [state.SirenOn] // if the Siren is on, only allow to turn it off
    {
      on TurnOff: state = State.SirenOff;
      on TurnOn:  illegal;
    }
  }
}

If you have questions that weren’t answered by this Guide,
let our support team help you out.

Enjoy this article? Don't forget to share.