Returning Values

Learn how to return values from functions including values from recursive functions.

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 main function is made to return 0 to 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 numbersFibonacci. Fibonacci numbers are defined as:

F0=0F1=1Fn=Fn1+Fn2where n2\begin{align*} F_0&=0\\ F_1&=1\\ F_{n} &= F_{n-1} + F_{n-2} \quad \text{where } n\geq 2 \end{align*}

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy