Why cant a function return more than one value?

Shalmanese

Platinum Member
Sep 29, 2000
2,157
0
0
I don't quite know if this is highly technical enough but why is it that every programming language I have ever used specifies that functions return one and only one value? I know that its technically not a function if it returns two things but seeing as how trivial yet annoying it is to try and have a function return two things, why has this requirement not been relaxed for more modern languages?

I've programmed in a fair few rather obscure ones and read about a lot more so I'm pretty certain its not present in any modern, widely used language. I can see many ways it could be handy so its odd that nobodys done this. Is there some advanced theoretical compiler theory that makes this difficult?
 

WooDaddy

Senior member
Jan 4, 2001
358
0
0
Pass in variables by reference and have the function change and return the additional info you want, holmes.

Effective coding means functions are modular, easy to understand and have few inputs and outputs.

Read Effective C++ by Scott Meyers. A lot of professional software engineers SWEAR by this book and once you start reading it, you'll understand why as well.

A single return value may seem like a limitation but once you read the book, you'll understand that it almost guides you in the direction of writing effective, focused functions.

My 2c.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Originally posted by: Shalmanese
I don't quite know if this is highly technical enough but why is it that every programming language I have ever used specifies that functions return one and only one value? I know that its technically not a function if it returns two things but seeing as how trivial yet annoying it is to try and have a function return two things, why has this requirement not been relaxed for more modern languages?

I've programmed in a fair few rather obscure ones and read about a lot more so I'm pretty certain its not present in any modern, widely used language. I can see many ways it could be handy so its odd that nobodys done this. Is there some advanced theoretical compiler theory that makes this difficult?

Generally the return value is stored in the EAX register on x86, and one of the $vx (where x is 0-4, IIRC) registers on MIPS. It's an assembly coding convention which results in the "limitation" imposed on higher level languages. There is no fundamental reason you couldn't put your return values on the stack like you do with parameters... it just wasn't the historical convention. (There might be also some reasons not to use the stack, e.g. overhead of going to cache instead of a register).
 

gsellis

Diamond Member
Dec 4, 2003
6,061
0
0
Why does a function not return more than one value? Because it would then be a subroutine :D
 

Peter

Elite Member
Oct 15, 1999
9,640
1
0
Because function results are results in the spirit and sense of math expressions.
 

Rainsford

Lifer
Apr 25, 2001
17,515
0
0
Assembly convention, and because it's a bad idea. More functions that do simple things are better than fewer functions that do a lot of things. Encouraging complex functions that return lots of values is a bad idea because it makes your programming much less modular, and a lot harder to understand. I'm sure some high level language like Java could make it work, but like I said, it encourages bad programming practices.
 

KF

Golden Member
Dec 3, 1999
1,371
0
0
I have not programmed in a lot of languages. Pascal. C++ To my knowledge, although functions are required to return a single entity, it can be a compound object. That is sufficent to return as many values as you like. For instance, a class may consist of 3 values defining the x, y, and z coordinates of a point. Thats three values that can be returned. And I suppose that's why languages never bother with a function that returns multiple objects.

The deficiency might arise if the output values are inherently unrelated, in which case grouping them in a stucture or class would only be confusing. However, since all programming languages are terribly confusing when dealing with anything slightly complex, one more idiocy on top of the rest would not be much to get exercised about.

In practice, I believe input and output for compound objects is handled as a pointer to a structure internally, although you never have to deal with it that way as the programmer.

I don't see that it would be bad practice to have a function, or whatever you might care to call it, return multiple values, any more than having multiple input parameters. It could provide an organizing logic to some situations. It seems to me that grouping both inputs and outputs together as input parameters obscures the program logic. Multiple outputs would add another complexity to the language design, true.
 

Peter

Elite Member
Oct 15, 1999
9,640
1
0
Functions are math. Math is always (Input parameters) stuck into a (function), giving a single (result). If (result) uses more than one value, e.g. if it's an N-dimensional vector of some sort, define an appropriate encapsulation data type. That brings you back to the one-result rule in no time, and THAT is what makes your program readable.

E.g. in C if you do 3D math you don't shuffle about with X, Y, and Z. Define a struct{X,Y,Z}, address as item.X, item.Y, item.Z. You can pass those struct entities into functions, and get entire XYZ tuples as a result.

So, there's no point in having multiple results from a single function. Clean up your code. IMHO.
 

zephyrprime

Diamond Member
Feb 18, 2001
7,512
2
81
These nothing to prevent returning more than one value. It's just a matter of pushing one more thing onto the stack.

And I think it'd be plenty useful to return more than one value also. There are many many functions that need to return one value and also one error code.
 

boran

Golden Member
Jun 17, 2001
1,526
0
76
dunno what you'd want to achieve, but in java i'd work with objects or arrays, or like I often do with a whole lote of info from different types, an ArrayList.
might not be performant, but it works.
 

WooDaddy

Senior member
Jan 4, 2001
358
0
0
I'd have to agree with Peter on this one too,

I'd hate to spark a flame war (even though my side will win :cool: ), but Peter's first response is essentially the ultimate truth for functions. This is defined in the hardware as well. When you perform ASM operations, they return a single value whether it be on the stack, EAX, or any other random register or memory location. Simplicity = readability = supportability = modularity = less cost = less development = easier development = less lost sleep = ounce of prevention = and so on. Passing multiple results (even as referenced pointers) reduces modularity and makes what you are working on, unnecessarily complex. In C++, using objects makes passing of more attributes/variables easier but only as long as you have a well defined base class and you inherit appropiately.

As a professional software engineer, I usually have discussions, which really are arguments, on which way is better. At the root of the discussions, it's basically "I'm lazy and I just want to write something quick, crappy and unplanned which will cost us MONTHS or YEARS of debugging costs instead of taking an extra day or too to actually plan out the software I need to design and getting it right the FIRST time". When developing code, effective programmers use tools such as Visio, Rational Rose and yes, pencil and paper (I like whiteboards) to flowchart and define the process. Even on a personal basis, when you look back at what you were trying to code, you'll realize just how much easier it is when you've simplified your code at the function level.

My 2 cents... but believe me, if you want a GREAT career in coding, follow this and you'll have accolades like you wouldn't believe.
 

Shalmanese

Platinum Member
Sep 29, 2000
2,157
0
0
I'm aware of good coding and all that jazz and in truth, 99% of the time, I wouldn't dream of using multi-return functions. But it's just those 1% of times where a function absolutely, positively cannot work with one return value where it gets so frustrating. Given how simple, yet clunky it is to do in most languages, its always been a mystery why it hasn't been integrated into the language. The most prominent example that comes to mind is how linux does error handling in the OS. Because it makes no presumptions as to the return value of functions (ie: it can't say that -1 is the universal return for errors because some functions have -1 as a meaningful return value), it cannot enforce a global scheme for error checking To do error checking, it requires that all functions have at least one return value that denotes errors (whch changes from function to function and requires a lot of man page reading and sometimes severewly hampers the function because all return values are meaningful). It then has a global variable errno which functions are expected to set. The problem with this is that if you call two functions in a row, then the errno from the first gets erased. This has always seemed like a hugely botched up and clunky system to me and I can see several far more elegant solutions.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Originally posted by: Shalmanese
I'm aware of good coding and all that jazz and in truth, 99% of the time, I wouldn't dream of using multi-return functions. But it's just those 1% of times where a function absolutely, positively cannot work with one return value where it gets so frustrating. Given how simple, yet clunky it is to do in most languages, its always been a mystery why it hasn't been integrated into the language. The most prominent example that comes to mind is how linux does error handling in the OS. Because it makes no presumptions as to the return value of functions (ie: it can't say that -1 is the universal return for errors because some functions have -1 as a meaningful return value), it cannot enforce a global scheme for error checking To do error checking, it requires that all functions have at least one return value that denotes errors (whch changes from function to function and requires a lot of man page reading and sometimes severewly hampers the function because all return values are meaningful). It then has a global variable errno which functions are expected to set. The problem with this is that if you call two functions in a row, then the errno from the first gets erased. This has always seemed like a hugely botched up and clunky system to me and I can see several far more elegant solutions.

WHy is it harder to check errno than to check the function's return value?
 

Hector13

Golden Member
Apr 4, 2000
1,694
0
0
Not sure what "languages" you have programmed in, but I believe both common lisp and matlab support multiple return values. To a lesser extenct, so do python and ruby. For matlab in particular, multiple return values are used all the time like:

[ a, b, c ] = some_function(x, y, z)
 

Peter

Elite Member
Oct 15, 1999
9,640
1
0
That'd be

struct point {x,y,z}

newpoint = some_function(point)

when properly done in a programming language. It's not multiple return values, it's one multi-dimensional result.
 

Hector13

Golden Member
Apr 4, 2000
1,694
0
0
Originally posted by: Peter
That'd be

struct point {x,y,z}

newpoint = some_function(point)

when properly done in a programming language. It's not multiple return values, it's one multi-dimensional result.

that could be... but it's not. Despite what you may believe, the way you are comfortable with is not necessarily the "proper" way.

Matlab allows you to determine how many return variables have been requested (while inside the function). Imagine a function that determines the eigenvalues of a matrix. It would look like V = eig(A).

Now, imagine that you'd also like the eigenvectors of the matrix. Getting the eigenvalues is 90% of way there. So, do you want another function that would duplicate 90% of the work and almost double the amount of time taken? Or would you prefer [ V, D ] = eig(A)?

The eig function can be smart enough to not waste time figuring out the eigenvectors if you don't ask for them.

NOTE: this example is contrived and the "90%" number is made up... it is too early for me to think of a better example right now, but this comes up over and over again in matlab code.
 

crimson117

Platinum Member
Aug 25, 2001
2,094
0
76
Originally posted by: Shalmanese
I don't quite know if this is highly technical enough but why is it that every programming language I have ever used specifies that functions return one and only one value? I know that its technically not a function if it returns two things but seeing as how trivial yet annoying it is to try and have a function return two things, why has this requirement not been relaxed for more modern languages?

I've programmed in a fair few rather obscure ones and read about a lot more so I'm pretty certain its not present in any modern, widely used language. I can see many ways it could be handy so its odd that nobodys done this. Is there some advanced theoretical compiler theory that makes this difficult?
pl/sql (oracle database stored procedures) you can use procedures to have as many IN, OUT, and IN/OUT parameters, effectively allowing your fucntion/procedure alter/return as many variables as you want. But like others have said, normalized functions return one value. If you need to return two values, then you need two functions.

If you really must return two values, concatenate the values into a single string (delimited by a bell char or something). But eventually you'll need another function (whether it's a separate function or just code in the main section), to decode that string.

What two values did you want returned? What language are you using? You could declare an object class that has two attributes, and return that object.

But be really sure you wouldn't be better off with two functions.
 

GoHAnSoN

Senior member
Mar 21, 2001
732
0
0
Originally posted by: gsellis
Why does a function not return more than one value? Because it would then be a subroutine :D

i agree on this.
and , hw support for one return function is simply unrelatted.
my 2 cents.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
In C you can return a struct, which could contain a bunch of things. In C++, you could do the same, as well as return a more "anonymous" compound object like a std::pair or a boost::tuple (boost::tuple will also be in the next revision of the c++ standard). In Python I can just do:

def blah(): return 1, 2, 3, 4

one, two, three, four = blah()

In reality this creates a tuple and returns it. Python lets you assign objects to a tuple's elements with the syntax used on the second line.

Honestly I don't think there's much point in allowing a function to truly return multiple items, when it's so easy to just use compound objects that can do that, without adding to the complexity of the language itself.

And there's also the ability to pass in things by pointer/reference. They're not "returned" via the normal syntax, but it achieves something pretty similar.

int my_parse_int_func(const char *, int *);

int myint;
const char * blah = "123";

if(my_parse_int_func(blah, &myint))
printf("parsed! %d\n", myint);
else
printf("couldn't parse number\n");
 

Spencer278

Diamond Member
Oct 11, 2002
3,637
0
0
Originally posted by: Peter
Functions are math. Math is always (Input parameters) stuck into a (function), giving a single (result). If (result) uses more than one value, e.g. if it's an N-dimensional vector of some sort, define an appropriate encapsulation data type. That brings you back to the one-result rule in no time, and THAT is what makes your program readable.

E.g. in C if you do 3D math you don't shuffle about with X, Y, and Z. Define a struct{X,Y,Z}, address as item.X, item.Y, item.Z. You can pass those struct entities into functions, and get entire XYZ tuples as a result.

So, there's no point in having multiple results from a single function. Clean up your code. IMHO.

Doesn't integer division give two results? The part you care about and then their is the remander. I know on the 68K that it produces to results part is in the upper 16 bits and the other part is in the lower 16 bits.

The main reason is for readibity and it makes life simpler because it tends to encourage people to make structs and classes.

Scheme kind of supports multiply return values by returning pairs.
 

CTho9305

Elite Member
Jul 26, 2000
9,214
1
81
Originally posted by: Spencer278
Doesn't integer division give two results? The part you care about and then their is the remander. I know on the 68K that it produces to results part is in the upper 16 bits and the other part is in the lower 16 bits.

Division is one of the few operation that requires writeback to more than one register. The vast majority only update one.
 

Shalmanese

Platinum Member
Sep 29, 2000
2,157
0
0
I would have like the >> and << functions to return 2 values, the bit pushed off and the remaining bits. It would simplify a lot of my code
 

sao123

Lifer
May 27, 2002
12,653
205
106
For my programming, one of the more useful times I would like to return 2 items is:

I want an error flag in addition to my return data.

for example...

In a calculator program...(although exceptions might make better code) I cant use -1 for error code, because that would be a valid result. I would like to return an error flag.



shalmanese....what exactly are you doing that would require << or >> to return 2 items...
I'm interested in this program...
 

Peter

Elite Member
Oct 15, 1999
9,640
1
0
Originally posted by: Shalmanese
I would have like the >> and << functions to return 2 values, the bit pushed off and the remaining bits. It would simplify a lot of my code

Do it in assembly language then. You'll get the register contents shifted, and the bit that's fallen off the far end in the Carry flag of the CPU.