I don't like 'out' function arguments, from a logic point of view they feel
unnatural and backwards (while 'ref' arguments are meaningful from a computer
science point of view). I'd even like to see 'out' arguments deprecated when
multiple return values are introduced as a bit of built-in syntax sugar for
tuple de-structuring.
Beside their bad look, D 'out' arguments have some semantic characteristic
that's bad:
Currently D allows you to write code like this, where foo lacks any assignment
to its 'out' argument (I think the Ada compiler raises a compilation error
here):
void foo(out int x, out int y) {}
void main() {}
The D compiler also sees nothing wrong in code like this:
void foo(out int x, out int y) {
x = 3;
y = 4;
}
void main() {
int x = 1;
int y = 2;
foo(x, y);
}
But to me this looks like possible bug waiting to happen, because the values 1
and 2 of x and y are always ignored, so they are always useless assignment (and
at the call point you don't write something like this: foo(out x, out y); so
you don't see that the x and y values will be ignored by foo).
A tuple syntax to return and unpack values (the pull request is already in
GitHub) avoids all three problems, because the syntax is more logical, it's
less easy to return values from foo without initializing them, and there is
less risk of losing values of the return tuple if you initialize variables in
place:
(int x, int y) foo() {
return tuple(3, 4);
}
void main() {
(int x, int y) = foo();
// auto (x, y) = foo(); // supported alternative
}
Bye,
bearophile