It tells the thing that’s interpreting or compiling your code that you want to exit the current function. If you just write ‘return’ that’s all that will happen, but typically you can also follow this up with some values that you want the function to spit out, i.e. the output of the function.
For instance, I could define this function (in python code):
def PlusTwo(x):
x+=2
return x
And then if in a command terminal (or some other script/function) I say:
> y = PlusTwo(3)
The resulting value of y will be 5.
You’ll often find return statements at the end of a function, but not necessarily. You can have different conditions under which you want the function to exit, with different outputs, and these might be found at different places in the function. However you nearly always find a return statement on the very last line of the function, because anything below that would be ignored. For instance, if I define a function like this:
def PlusTwo(x):
x+=2
return x
x+=7
the last line will never actually be executed, and so this function still just adds 2 to the value of x.
Some languages don’t require return statements – you just have to specify in the function definition what variables are your output variables. And then whatever the values of those variables are when the function exits will be your output. MATLAB for instance works this way. But others, like C or python, do use return.
Latest Answers