Return
The return statement is a kind of jump statement that ends the current function or procedure. In a function, you 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 end the current function or procedure. In a function, you must end with a return statement to provide the value to be returned to the caller. However, you can also use a return statement to exit out of a procedure before reaching the end of its code.
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 function 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 have provided the exact value.
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.
#include "splashkit.h"
using std::to_string;
int test_return(){ write_line("test-return started"); return 3; write_line("Cannot be run as code returned above!");}
int main(){ write_line("Calling test_return - the value " + to_string(test_return()) + " is returned\n"); return 0;}
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.