Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do functions in some popular languages return only a single type of result?

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(){
.......
........
}
like image 785
Sagar Varpe Avatar asked Jul 16 '10 07:07

Sagar Varpe


People also ask

Why can a function only return one value?

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.

Which programming language can return multiple?

Among popular languages, Ruby and Python both allow returning multiple variables directly.

Can a function have multiple return keyword?

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.

How do I return multiple parameters in Python?

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.


3 Answers

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).

like image 120
Markos Avatar answered Oct 14 '22 15:10

Markos


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.

like image 24
Groo Avatar answered Oct 14 '22 17:10

Groo


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.

Related questions

  • Using a java method to return multiple values?
  • Returning multiple values from a C++ function
  • Returning multiple values from a C function
  • Method should return multiple values
  • Elegant ways to return multiple values from a function
like image 32
polygenelubricants Avatar answered Oct 14 '22 17:10

polygenelubricants