Returning Values
Learn how to return values from functions including values from recursive functions.
We'll cover the following...
A function can return a value using the return keyword. To avoid unexpected errors, the value returned by a function should be compatible with the return type of the function.
For instance, the return 0; statement we have seen at the end of the main functions returns an integer which is compatible with the return type int listed right before the function name main.
Note: By convention, the
mainfunction is made to return0to indicate that the program has run to completion with success.
Functions whose return type is void don’t return anything.
Example: A function that computes
Let’s consider another example of a function, one where we want our function to do some computations and return the computed value. Let’s write a function to compute Fibonacci numbers. Fibonacci numbers are defined as:
...