Return
The return statement is a kind of jump statement that ends the current function or procedure. This is useful for skipping the rest of function or procedure’s block, and returning early to the calling code. In a function, you also use the return statement to provide the value that is sent back to the caller.
Return — when, why, and how
There are a couple of reasons why you may want to add a return statement to exit out of the current function or procedure. This includes providing a value from a function, which is the most common use, but can also be used to exit early under certain conditions.
When you use a return statement to exit a function or procedure early, you need something like an if statement that checks if you should exit, and then put the return statement within the body of the if. This can be used when you know that the procedure or functions only works in certain circumstances. For example, in the change calculator we could exit early if the user has not paid enough for the item, or if they have provided the exact right amount.
In C/C++
A return statement is quite simple — it is the word “return”, followed by an optional expression, then a semicolon. The use of an expression depends on whether you are using the return statement in a function or procedure:
- In a function, a return statement must have an expression.
- In a procedure, a return statement must not have an expression.
This is because a function returns a value, whereas a procedure does not.
When the return statement is executed the function or procedure ends and control is passed back to the calling statement. If the return statement is in a function, the expression is evaluated and the value is returned to the caller.
Examples
The following code shows the use of a return statement.
Note how the final line in test_return
does not execute because the return statement is before it in the sequence of instructions.
Let’s explore how this code works.
For other examples, have a look back at the example using parameters. The square
function uses the return statement to return the squared value, while point_in_circle
returns the value from the comparison to indicate if the point is within the circle.