mentioned that it is legal for one function to call another, and we
have seen several examples of that. I neglected to mention that it is
also legal for a function to call itself. It may not be obvious why
that is a good thing, and often it isn’t, but it turns out to be one of
the things a program can do. It is also one of the required subjects
covered in the Advanced Placement tests for computer programming.
Note / Caution: There are
a few well known pitfalls associated with recursive programming. The
first, and most obvious, is that you can program a sequence of
functional calls that never ends (until you shut off your computer).
This is the most likely problem area with WCM. If you do use recursion,
the recursive sequence should be very carefully thought out.
Second, many programs in
general (though not WCM scripts) allow real time input from the
keyboard, mouse or an external source. Should an interrupt occur during
the recursive sequence, the results may be unpredictable but are seldom
good. A similar situation occurs if many different program parts
(called threads) are running at the same time (again not an issue with
WCM). There are very stringent requirements for programming in this
environment, which are well beyond the scope of this book, which should
be carefully studied before attempting to program in a multi-threaded
environment, especially using recursion.
For example, look at the
void CountDown (
int iN )
( iN == 0 )
ShowText ( iN );
CountDown ( iN-1 );
The name of the function is CountDown and it takes a single integer as a
parameter. If the parameter is zero, it outputs the word “
START!!!” Otherwise, it outputs the parameter and then calls a function
named countdown – itself – passing iN-1 as an argument.
What happens if we call this function like this
void Scene1 ()
CountDown ( 3 );
The execution of countdown begins with n=3, and since n is not zero, it
the value 3, and then calls itself...
The execution of countdown begins with n=2, and since n is not zero,
it outputs the value 2, and then calls itself...
The execution of countdown begins with n=1, and since n
is not zero, it outputs the value 1, and then calls itself...
The execution of countdown begins with n=0, and
since n is zero, it outputs the word “START!!!” and then returns.
The countdown that got n=1
The countdown that got n=2
The countdown that got n=3
And then you are back
to Scene1 (what a trip). So the total output looks like this:
Recursion is a very powerful feature of C++ but it is not used very
often in cartoons. We do not want to spend a lot of time in this book
teaching you about recursion, but you are welcome to do your own
experiments. If you do, be careful.