Return statement

Updated: 04/26/2017 by Computer Hope

return statementIn programming, return is a statement that tells the program to leave the subroutine and return to the return address, directly after where the subroutine was called. In most programming languages, the return statement is either "return" or "return value", where value is a variable or other information coming back from the subroutine. Below is an example of how the return statement could be used in the Perl programming language.

my $rsexample = 1;

print "Example of a return statement.\n";
&rsexample;
print "Value now equals: $rsexample\n";

sub rsexample {
$rsexample++;
return $rsexample;
}

In the above example, the rsexample variable is first set as equal to 1 and then when the rsexample subroutine is called that value is increased by 1. When the program returns to the return address the program prints "Value now equals: 2". Unlike some other programming languages, if Perl does not have a return statement in the subroutine it returns the statements last value. In the above example, the code would still work the same even if the return statement wasn't in the subroutine.

In the example below (using JavaScript), the function returns back to the code that called it if the number sent to the function is less than one.

function a (num) {
if (num < 1) {
return;
}
else {
document.write("The number is" + num + "<br />);
}
}
a(0);
document.write("I like numbers greater than 0");

In this case, the number sent to the function is 0, so the function returns back to the code after the function call, and will write the text "I like numbers greater than 0". If the number were instead 1, then the text "The number is 1" would be written first, and the text "I like numbers greater than 0" would be written below it.

If a programming language allows the return statement to return a value back to the code, then the returned value can be used in the code that called the function. The code below (again using JavaScript) shows an example of how this is done.

function a (num) {
if (num < 1) {
return false;
}
else {
return true;
}
}
var x = a(0);
if (x === true) {
document.write("The number is greater than 0");
}
else {
document.write("The number is not greater than 0");
}

In this case, the result of the function (the return value) is assigned to the variable x. The function returns the value true if the number sent to it is greater than one, and returns the value false otherwise. Since the value sent to the function in this case is 0, the function returns as false. This returns the function to the conditional statement, which will write The number is not greater than 0 on the page, since the value returned to the variable x is false.

Programming terms, Return, Return address, Subroutine