[prev] 50 [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:

// Euclid's gcd algorithm (recursive version)
int euclid_gcd(int m, int n) {
    if (n == 0) {
        return m;
    } else {
        return euclid_gcd(n, m % n);
    }
}

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

return;