Recursion
C permits a function to call itself. This process is termed recursion. Recursion is a sometimes tricky, sometimes convenient tool. It's tricky to get recursion to end because a function that calls itself tends to do so indefinitely unless the programming includes a conditional test to terminate recursion.
Recursion Revealed
To see what's involved, let's look at an example. The function main() in Listing 9.6 calls the up_and_down() function. We'll term this the "first level of recursion." Then up_and_down() calls itself; we'll call that the "second level of recursion." The second level calls the third level, and so on. This example is set up to go four levels.
Listing 9.6 The recur.c program.
/* recur.c -- recursion illustration */ ... |
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.