Return statement

Updated: 11/13/2018 by Computer Hope
return statement

In programming, return is a statement that instructs a program to leave the subroutine and go back to the return address. The return address is located 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 example above, the rsexample variable is first set as equal to 1. 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 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 JavaScript below, the function returns to the code that called it if the number sent 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 to the code after the function call, and writes 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 send a value back, then that 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. In the example above, because the value sent to the function is 0, the result returns as false. The function continues evaluating the conditional statement, which writes "The number is not greater than 0" on the page, because the value returned to the variable x is false.

Programming terms, Return, Return address, Subroutine