Menu

Using Functions

Functions are defined in a behaviour section.

These functions can be called as part of an action.

Functions can access global variables.

Syntax

Function declaration:

return-type function-name (parameter-list)
{
  function-body;
}

A function definition consists of a function header and a function body.

Here are all the parts of a function:

  • return-type: The return-type is the data type of the value the function returns. Use the keyword void for functions that do not return a value.

  • function-name: This is the actual name of the function.

  • parameter-list: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

  • function-body: The function body contains a collection of statements that define what the function does.

Examples

A basic function

This example shows an interface with a behaviour section where a function is defined and used to determine the proper actions.

interface IFunctionCallAction
{
  in void doIt();
  out void done();
  out void skip();

  behaviour
  {
    enum Toggle {On, Off};
    Toggle state = Toggle.On;

    bool shouldWeDoIt()                  // the function returns a Boolean value, is called shouldWeDoIt and has no parameters
    {
      bool result = false;
      result = (state == Toggle.On);
      return result;                     // the result of the evaluation is returned
    }

    on doIt:
    {
      bool localVariable = shouldWeDoIt(); // the function is called and the return value stored in localVariable

      if (localVariable)
      {
        done;
        state = Toggle.Off;
      }
      else
      {
        skip;
        state = Toggle.On;
      }
    }
  }
}
Enjoy this article? Don't forget to share.