Functions

Functions can be declared the same places as 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 ] ';'

where the Declarations non-terminal is defined in the section on declarations and the Parameters non-terminal is defined in the section on types.

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. It is however important to that for iterates over the elements of a type, whereas in Java is iterates over collections (e.g. arrays).

The scope of ID is the inner statement.

Examples

add

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

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

swap

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

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

initialize

The following procedure initializes an array such that each element contains its index in the array. Notice that as in C, the parameter is a call-by-reference parameter even though no ampersand it used in the declaration.

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