Return Statement

Dave Braunschweig and Kenneth Leroy Busbee

Overview

A return statement causes execution to leave the current function and resume at the point in the code immediately after where the function was called. Return statements in many languages allow a function to specify a return value to be passed back to the code that called the function.[1]

Discussion

The return statement exits a function and returns to the statement where the function was called. Most programming languages support optionally returning a single value to the calling function. Consider the following pseudocode:

Function Main
    ...
    Assign fahrenheit = GetFahrenheit()
    ...
End

Function GetFahrenheit
    Declare Real fahrenheit
    
    Output "Enter Fahrenheit temperature:"
    Input fahrenheit
Return Real fahrenheit

In English, the Main function calls the GetFahrenheit function, passing in no parameters. The GetFahrenheit function retrieves input from the user and returns that input back to the main function, where it is assigned to the variable fahrenheit. In this example, the Main function has no return value.

Note that functions are independent, and each function must declare its own variables. While both functions have a variable named fahrenheit, they are not the same variable. Each variable refers to a different location in memory. Just as parameters by default are passed by position rather than by name, return values are also passed by position rather than by name. The following code would generate the same results.

Function Main
    ...
    Assign fahrenheit = GetTemperature()
    ...
End

Function GetTemperature
    Declare Real temperature
    
    Output "Enter Fahrenheit temperature:"
    Input temperature
Return Real temperature

Most programming languages support either zero or one return value from a function. There are some older programming languages where return values are not supported. In those languages, the modules are often referred to as subroutines rather than functions. There are also programming languages that support multiple return values in a single return statement, however, only single return values or no return value will be used in this book.

Key Terms

return
A branching control structure that causes a function to jump back to the function that called it.

References


License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Authors and Contributors is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book