Sams Teach Yourself C++ in 21 Days

(singke) #1
By the time your program executes, the instructions are already in place, compiled into
the .objfile. This saves a jump and return in the execution of the code at the cost of a
larger program.

124 Day 5


The inlinekeyword is a hint to the compiler that you want the function to
be inlined. The compiler is free to ignore the hint and make a real function
call.

NOTE

Recursion ........................................................................................................


A function can call itself. This is called recursion, and recursion can be direct or indirect.
It is direct when a function calls itself; it is indirect recursion when a function calls
another function that then calls the first function.
Some problems are most easily solved by recursion, usually those in which you act on
data and then act in the same way on the result. Both types of recursion, direct and indi-
rect, come in two varieties: those that eventually end and produce an answer, and those
that never end and produce a runtime failure. Programmers think that the latter is quite
funny (when it happens to someone else).
It is important to note that when a function calls itself, a new copy of that function is run.
The local variables in the second version are independent of the local variables in the
first, and they cannot affect one another directly, any more than the local variables in
main()can affect the local variables in any function it calls, as was illustrated in
Listing 5.3.
To illustrate solving a problem using recursion, consider the Fibonacci series:
1,1,2,3,5,8,13,21,34...
Each number, after the second, is the sum of the two numbers before it. A Fibonacci
problem might be to determine what the 12th number in the series is.
To solve this problem, you must examine the series carefully. The first two numbers are


  1. Each subsequent number is the sum of the previous two numbers. Thus, the seventh
    number is the sum of the sixth and fifth numbers. More generally, the nth number is the
    sum of nā€“2 and nā€“1, as long as n > 2.
    Recursive functions need a stop condition. Something must happen to cause the program
    to stop recursing, or it will never end. In the Fibonacci series, n < 3 is a stop condition
    (that is, when n is less than 3 the program can stop working on the problem).

Free download pdf