[DIP idea] out variables
Dukc
ajieskola at gmail.com
Thu Jan 28 09:17:47 UTC 2021
On Tuesday, 26 January 2021 at 01:01:54 UTC, Q. Schroll wrote:
> In current semantics, `out` is basically `ref` but with
> documented intent.
It is more, at least potentially: an optimization aid. The
calling function knows that contents of the `out` variable won't
affect the result, unlike with `ref`.
> General Idea
> ============
>
> The idea of an out variable is one that **must** be passed to a
> function in an `out` parameter position. Basic example:
>
> int f(out int value);
> int g(int[] value...);
> int h(out int a, out int b);
>
> out int x;
> // g(x); // illegal: reads x, but x is not yet initialized.
> // h(x, x); // illegal:
> // reads the second x before the initialization of
> first x is complete.
> f(x); // initializes x.
I don't like this. It is going to get annoying in cases like this:
```
int f(out int, int);
int func()
{ out int x;
if(someCond) x.f(0);
else if(someOtherCond) x.f(1);
return x;
}
```
What should the compiler do? It cannot know whether it's possible
x can be returned uninitialized. It can issue an error just in
case, and we hate to refactor code due to false alarms like that.
Or it can ignore it, in which case the `out` storage parameter
will sometimes work, sometimes silently fail. One is still going
to need to void initialize stuff to be sure to elide the default
initialization.
> In-place `out` Variables
> ========================
>
> When calling a function with an `out` parameter, instead of
> passing an argument, a fresh variable can be declared instead:
>
> if (f(out int x) > 0 && x > 0) { g(x); } else { .. }
> if (g(0) && f(out x) > 0) { g(x); } else { .. }
>
This, however, sounds better. I'd only leave out the requirement
for the caller to specify `out`, and also let to do that for
`ref` parameters.
More information about the Digitalmars-d
mailing list