As an example, we’ll write a function to determine the factorial of a given number. The factorial of a number n
is the product of the numbers from 1 through n
. The factorial of 5, for example, is 120.
1 * 2 * 3 * 4 * 5 = 120
We might define this function as follows:
// factorial of val is val * (val - 1) * (val - 2) . . . * ((val - (val - 1)) * 1)
int fact(int val)
{
int ret = 1; // local variable to hold the result as we calculate it
while (val > 1)
ret *= val--; // assign ret * val to ret and decrement val
return ret; // return the result
}
Our function is named fact
. It takes one int
parameter and returns an int
value. Inside the while
loop, we compute the factorial using the postfix decrement operator (§ 4.5, p. 147) to reduce the value of val
by 1 on each iteration. The return
statement ends execution of fact
and returns the value of ret
.