Comp 110 Return Statements and Return Addresses

What is a Return Statement?

return statement occurs within function calls. This is a way for your computer to send a result back to the function was called and where we dropped a "bookmark" within the program. A function will only execute ONE return statement before exiting a function. 

That place where we dropped a "bookmark" is referenced in environment diagrams as the ra box, which stands for return address. This is the spot where you write the line on which the function was originally called, so you know where to return to once the function call is complete.

Returning in Environment Diagrams

Recall that every time a new function is called in a program, a new frame is added onto the stack. The ra box will hold the line on which the function is called. As we work through the function, we work within the frame. What happens when we reach the return statement?

Once you know the value of what is being returned, enter that value in a box named rv in the current frame. 

This value is then returned to where the function call originated. If the function call was part of a variable assignment, copy the return value into the variable name it is being returned to in the main function

The Return Statement has been reached...what now?

Behind the scenes in your computer, once a function call has returned a value, its environment and state (AKA its frame) is erased. Because we are working on paper, we will not be physically erasing frames from the stack. However, if a frame has an rv entry, that frame is ignored.