Writing a Function

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 ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.