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 115:
add(3, 11)
return 1 + add(2, 11)add(2, 11)
return 1 + add(1, 11)add(1, 11)
return 1 + 116:
add(3, 11)
return 1 + add(2, 11)add(2, 11)
return 1 + 127:
add(3, 11)
return 1 + 138:
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.