www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - multiple return

reply %u <asmasm hotmail.com> writes:
I have function which have more than one return, and the code compile and run
but it gives rong result -I guess-, so i use tuple but the compiler can't
return tuple.

how can I return values?
why I can't return tuple?
Apr 19 2011
next sibling parent bearophile <bearophileHUGS lycos.com> writes:
%u:

 I have function which have more than one return, and the code compile and run
 but it gives rong result -I guess-, so i use tuple but the compiler can't
 return tuple.
 
 how can I return values?
 why I can't return tuple?
Currently in D there are two ways to return multiple values from a function: - To use a std.typecons.tuple (not a std.typetuple). - To use "out" function arguments. Regarding typetuples, they can't be used to return multiple values from a function because of differences in stack alignment, this means incompatible ABI of D functions and D typetuples. This is not a great thing, but I presume that doing otherwise breaks a "zero overhead" constraint Walter seems to require to D typetuples. Given the presence of typecons tuples (and maybe in future some syntax sugar to use them in a more handy way), this is not a significant limitation. It's mostly strange to have two very different kinds of tuples in a single language. Bye, bearophile
Apr 19 2011
prev sibling next sibling parent Max Klyga <max.klyga gmail.com> writes:
On 2011-04-20 01:35:46 +0300, %u said:

 I have function which have more than one return, and the code compile and run
 but it gives rong result -I guess-, so i use tuple but the compiler can't
 return tuple.
 
 how can I return values?
 why I can't return tuple?
In D, tuple is not built in type, it is defined in stantard library. To use it, you must import module std.typecons Example: import std.typecons;   struct Foo {}   Tuple!(int, string, Foo) baz() {     // some computation here     return tuple(13, "inches", Foo()); }   void main() {     auto bar = baz();     assert(bar == tuple(13, "inches", Foo())); }
Apr 19 2011
prev sibling parent reply %u <asmasm hotmail.com> writes:
thanks you all, it works.

last thing, I have this
Tuple!(int,int,int)(1, 2, 3)

how can I use the return values individual?

to be more clear if I rturn tuple(a, b, c) can I write in the code

void main() {

//call the function here
writeln(a);

}
Apr 20 2011
parent bearophile <bearophileHUGS lycos.com> writes:
%u:

 how can I use the return values individual?
One of the simpler ways is to think of a tuple as an array, and use sometuple[0] to take its first item, etc. But your tuple indexes need to be compile-time constants. Bye, bearophile
Apr 20 2011