index

References

Passing variables by references to and from functions allow for increased flexibility in the way you solve a problem. A function can normally only return one value, but by declaring the function to take a parameter by reference the function can use that reference to set a second return value.

A parameter is declared as reference by appending the symbol & followed by in, out, or inout. The word following the & symbol shows in which direction the value in the reference is passed, in to the function, out from function, or both.

void function(int &in a, int &out b)
{
  // The value of b will be returned to the calling function
  b = a;
  
  // The value of a is not returned to the calling function
  a = 0;
}

The term by reference, might be a bit misgiving, as it is not a reference to the actual value that is being passed to the function, but rather a reference to a value of the same type. If the reference is in or inout the value will have the same value as the expression calculated for the argument, otherwise it will be unitialized. If the reference is out or inout the value in the parameter will be copied back to the original variable when the function returns.

When the reference is in the argument expression is evaluated before the function call, and for out the expression is evaluated after the function returns. For inout the expression is evaluated twice, so be aware of this when using complex expressions for the function arguments.

As you might have guessed, it is not very useful to declare a parameter as &in because the value will be copied anyway. The only reason that this option is available is that some application functions might require it.

If possible, it is normally better to pass the objects using a handle instead of passing it by reference, because this will avoid a potentially expensive copy of the object.

top