Why do functions in some popular languages return only a single type of result?
i.e I mean Why The Compilers give Error on Following Syntax
public int int returnTwoIntegers(){
.......
........
}
So, if we write more than one return statement in our code, the control goes back to the calling function on occurence of first return statement itself. So,there is no question of returning more than one value. 2.
Among popular languages, Ruby and Python both allow returning multiple variables directly.
Answer. A function can have multiple return statements but only one of them will be executed because once a return statement is executed, the program control moves back to the caller function skipping the remaining statements of the current function.
In Python, you can return multiple values by simply return them separated by commas. In Python, comma-separated values are considered tuples without parentheses, except where required by syntax. For this reason, the function in the above example returns a tuple with each value as an element.
Functions return only one value because its the way "they" invented it in the old days of assembler. Basically what happens is that function pushes return value on the stack. Caller then pops the value from the stack. If function returned more values, caller wouldnt know how many values to pop and the stack would be unbalanced (leading to program crash).
A function (in languages you mentioned in your tags) does have a single output , but that output does not have to be a single value. Your output can easily be a class which encapsulates any amount of data you want.
Also, note that you can also pass multiple input arguments by reference to your function, thereby increasing the number of returned outputs.
To simplify matter.
You can always return a T[]
, Pair<L,R>
, Set<E>
, etc in these languages to emulate returning multiple values. That takes care of most multiple return
values scenarios out there.
It's not worth changing the semantics of the language so much for a gain so little.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With