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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access