< previous page page_410 next page >

Page 410
data type of Expression is different from the declared function type, its value is coerced to the correct type.)
In Chapter 7, we presented a syntax template for the function definition of a void function. We now update the syntax template to cover both void functions and value-returning functions:
0410-01.gif
If DataType is void, the function is a void function; otherwise, it is a value-returning function. Notice from the shading in the syntax template that DataType is optional. If you omit the data type of a function, int is assumed. We mention this point only because you sometimes encounter programs where DataType is missing from the function heading. Many programmers do not consider this practice to be good programming style.
The formal parameter list for a value-returning function has exactly the same form as for a void function: a list of parameter declarations, separated by commas. Also, a function prototype for a value-returning function looks just like the prototype for a void function except that it begins with a data type instead of void.
Let's look at two more examples of value-returning functions. The C++ standard library provides a power function, pow, that raises a floating point number to a floating point power. The library does not supply a power function for int values, so we'll build one of our own. The function receives two integers, x and n (where nþ 0), and computes xn. We use a simple approach, multiplying repeatedly by x. Because the number of iterations is known in advance, a count-controlled loop is appropriate. The loop counts down to 0 from the initial value of n. For each iteration of the loop, x is multiplied by the previous product.
int Power( /* in */ int x,    // Base number
           /* in */ int n )   // Power to raise base to

// This function computes x to the n power

// Precondition:
//     x is assigned  &&  n >= 0  &&  (x to the n) <= INT_MAX

 
< previous page page_410 next page >