There are cases where you just want to run a routine, follow an algorithm, a procedure, without generating results. It does an action but does not produce a value to be used in an expression. Each language can give a name and a way to treat this.
This is possible in virtually all languages. Some require this algorithm to have another name (procedure
, for example). I talk about this in What is the difference between functions and procedures?.
Mathematically speaking a function must return some value. Many languages allow them not to return because there is not much practical advantage to give another name just because it does not return a value.
In statically typed languages the normal is to define a return convention depending on its syntax. Some require the type to be void
(Java, for example) or some other name (unit
fashionable). Actually this is not usually a type of data effectively.
In dynamic typing languages it is normal for the function not to have a type, so returning a value or not, to the compiler, is the same. Of course, if you return "nothing" because you expect a value to return, it will be a logical error (which can be circumvented).
I have seen several cases of the function being confused and starts returning a value of a type, then there is a maintenance and it creates another execution path and returns without value. In dynamic languages (not all) this is usually possible since returning nothing is actually returning a null, which is still a value (other than a void
).
In theory these procedures do not need a command return
. If it exists, obviously it should not return value (or at least it will be discarded in static languages). Of course there are cases that the procedure needs to end before its last line. A command return
is for flow control and is used to finish the execution immediately.
Some languages, even in full functions (which return value), allow the return
is omitted to produce a result. But of course the command will always be necessary if you want to stop the execution before its end. This is the primary goal of all return
, return a value is only its secondary function. The word "return" must be read as "return to the calling place" and not "return a value". Exactly why it has language that even uses the variable Result
as default to identify what should be used as a result at the end of the function. Although everyone understands "return a value", the correct is "result a value and return to the caller".
Some languages allow more than one value to result (it is usually an internal trick).
On the right there is an important related question on the subject.
Wikipedia article on the return
. About the type of return.
Looks like a duplicate of Why should I only use a "Return" in each function?
– user28595
It’s not duplicate, that question you mentioned is about using one or several
return
in the body of a method. Mine refers to the use ofreturn
no attribute to return.– Leonardo