In most applications this will be no problem, but it is worth noting that each
call will add a newentry on the call stack. If stack space or memory is limited, this can
be a problem. In particular, if there are objects connected in a cycle, going round the
cycle will continually add new entries on the call stack, eventually running out of
memory.
The solution to this problem is to implement a kind of tail recursion. Tail recursion
may be familiar from functional languages, where many algorithms make use of
recursive function calls. Each invocation of the function at a new level of recursion
would normally add a new entry to the call stack. Only at the end of the algorithm
would all the calls unwind, with each simply returning its value to its caller. To prevent
stack over?¬‚ow, functional programmers noticed that there is actually no need to
maintain all the function invocations on the stack. The last step of the function is often
just to return the value of calling itself recursively. In that case, it is enough to maintain
one invocation of the function on the top of the stack, and each new call simply
overwrites that copy. At the end of the algorithm, the deepest invocation thus returns
its value directly to the caller of the ?¬?rst level of invocation.
While our function calls are not recursive, we can note that the last step in
each function is to call the next function.
Pages:
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540