Functions that return values
An example of a function that returns a value is the sqrt()
function. The sqrt()
function accepts a single parameter between its brackets (the number to root) and returns the actual root of the number.
Here's an example usage of the sqrt
function:
cout << sqrt( 4 ) << endl;
The sqrt()
function does something analogous to what the chef did when preparing the pizzas.
As a caller of the function, you do not care about what goes on inside the body of the sqrt()
function; that information is irrelevant since all you want is the result of the square root of the number that you are passing.
Let's declare our own simple function that returns a value, as shown in the following code:
int sum(int a, int b) { return a + b; }
The following screenshot shows the anatomy of a function with parameters and a returned value:
The sum
function is very basic. All it does is take two int
numbers a
and b
, sums them up together, and returns a result. You might say that...