[prev] 55 [next]

Functions (cont)

When a return statement is executed, the function terminates:

return expression;

  1. the returned expression will be evaluated
  2. all local variables and parameters will be thrown away when the function terminates
  3. the calling function is free to use the returned value, or to ignore it

Example:

int factorial(int n) {
    if (n == 0) {
        return 1;
    } else {
        return n * factorial(n-1);
    }
}

The return statement can also be used to terminate a function of return-type void:

return;