Skip to main content.

Functions

Functions can be declared alongside other declarations. The syntax for functions is defined by the grammar for Function:

Function        ::= Type ID '(' Parameters ')' Block 
Block	        ::= '{' Declarations Statement* '}'
Statement       ::= Block
                 | ';'
                 |  Expression ';'
	         |  ForLoop
		 |  Iteration
	         |  WhileLoop 
	         |  DoWhileLoop 
	         |  IfStatement 
		 |  ReturnStatement
ForLoop	        ::= 'for' '(' Expression ';' Expression ';' Expression ')' Statement 
Iteration	::= 'for' '(' ID ':' Type ')' Statement
WhileLoop       ::= 'while' '(' Expression ')' Statement
DoWhile         ::= 'do' Statement 'while' '(' Expression ')' ';'
IfStatment      ::= 'if' '(' Expression ')' Statement [ 'else' Statement ]
ReturnStatement ::= 'return' [ Expression ] ';'

Iterators

The keyword for has two uses: One is a C/C++/Java like for-loop, and the other is a Java like iterator. The latter is primarily used to iterate over arrays indexed by scalars.

A statement for (ID : Type) Statement will execute Statement once for each value ID of the type Type. The scope of ID is the inner expression Expr, and Type must be a bounded integer or a scalar set.

Examples

add

The following function returns the sum of two integers. The arguments are call by value.

 
int add(int a, int b)
{
    return a + b; 
}

swap

The following procedure swaps the values of two call-by-reference integer parameters.

void swap(int &a, int &b) 
{
  int c = a;
  a = b;
  b = c;
}

initialize

The following procedure initializes an array such that each element contains its index in the array. Notice that the an array parameter is a call-by-value parameter unless an ampersand is used in the declaration. This is different from C++ syntax, where the parameter could be considered an array of references to integer.

void initialize(int& a[10])
{
  for (i : int[0,9]) 
  {
    a[i] = i;
  }
}