Previous: Call by Value, Up: Calling Functions
With some restrictions1, recursive function calls are allowed. A recursive function is one which calls itself, either directly or indirectly. For example, here is an inefficient2 way to compute the factorial of a given integer:
function retval = fact (n) if (n > 0) retval = n * fact (n-1); else retval = 1; endif endfunction
This function is recursive because it calls itself directly. It eventually terminates because each time it calls itself, it uses an argument that is one less than was used for the previous call. Once the argument is no longer greater than zero, it does not call itself, and the recursion ends.
The built-in variable max_recursion_depth
specifies a limit to
the recursion depth and prevents Octave from recursing infinitely.
Limit the number of times a function may be called recursively. If the limit is exceeded, an error message is printed and control returns to the top level.
The default value is 256.
[1] Some of Octave's function are
implemented in terms of functions that cannot be called recursively.
For example, the ODE solver lsode
is ultimately implemented in a
Fortran subroutine that cannot be called recursively, so lsode
should not be called either directly or indirectly from within the
user-supplied function that lsode
requires. Doing so will result
in undefined behavior.
[2] It would be
much better to use prod (1:n)
, or gamma (n+1)
instead,
after first checking to ensure that the value n
is actually a
positive integer.