[   ^ to index...   |   <-- previous   |   next -->   ]

Recursion and the call stack

Recursion is more powerful than iteration (in fact, several languages omit explicit iteration constructs entirely). However, with that power, comes a cost: every time a procedure is called, an activation record must be allocated on the stack:

1:

add(3, 11)
return 1 + add(2, 11)

2:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)

3:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + add(0, 11)

4:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + add(0, 11)
add(0, 11)
return 11

5:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + add(1, 11)
add(1, 11)
return 1 + 11

6:

add(3, 11)
return 1 + add(2, 11)
add(2, 11)
return 1 + 12

7:

add(3, 11)
return 1 + 13

8:

14

Often, the recursive call in a recursive function immediately precedes a return point:

Node * findInList(int value, ListNode * node) { if (node == NULL || node->element == value) return node; else return findInList(value, node->next); }

In this case, an intelligent compiler can automatically transform a recursive procedure into an iterative one; this optimization is called tail recursion elimination. Unfortunately, most C/C++ compilers do not implement this optimization.


Last modified: Thu Jul 6 13:55:15 PDT 2000