vrijdag 22 juni 2007

Recursion

A C++ function has the interesting characteristic that it can call itself. (Unlike C, however C++ does not let main() call itself.) This ability is termed recursion. Recursion is an important tool in certain types of programming, such as artificial intelligengence, but we'll just take a superficial look (artificial shallowness) at how it works.

Recursion with a Single Recursive Call
If a recursive function calls itself, then the newly called function calls itself, and so on, ad infinitum unless the code includes something to terminate the chain of calls. The usual method is to make the recursive call part of an if statement. For example, a type void recursive function called recurs() can have a form like this:

void recurs(argumentlist)
{
statements1
if (test)
recurs(arguments)
statements2
}

With luck or foresight, test eventually becomes false, and the chains of calls is broken.

Recursive calls produce an intriguing chain of events. As long as the if statement remains true, each call to recurs() executes statements1 and then invokes a new incarnation of recurs() without reaching statements2. When the if statement becomes false, the current call then proceeds to statements2. Then when the current call terminates, program control returns to the previous version of recurs() that called it. Then, that version of recurs() completes executing its statements2 section and terminates, returning control to the prior call, and so on. Thus, if recurs() undergoes five recursive calls, first the statements1 section is executed five times in the order in which the functions where called, and then the statements2 section is executed five times in the opposite order from the order in which the were called. After going into five levels of recursion, the program then has to go back out through the same five levels.

Geen opmerkingen: