One of the thing I like in D
Dave P.
dave287091 at gmail.com
Sat Oct 12 04:17:49 UTC 2024
On Friday, 11 October 2024 at 23:04:20 UTC, Per Nordlöw wrote:
> On Monday, 7 October 2024 at 20:03:46 UTC, Boaz Ampleman wrote:
>> [...]
>>
>> It's just beautiful
>
> With next dmd you can use use ref variables aswell as
>
> ```d
> void main() {
> auto a = 0;
> auto b = 0;
> const c = 1;
>
> ref ptr = (c ? a : b);
> ptr = 8;
> assert(a == 8);
> ptr = (c ? b : a);
> ptr = 2;
> assert(b == 2); // why does this fail??
> }
> ```
>
> But for some reason the last statement doesn't behave as I
> believe it should. Is this behavior expected?
>
> For reference see
> https://dlang.org/changelog/pending.html#dmd.reflocal.
`ref` can’t change what it is pointing to. So the second ternary
is just assigning through the reference, not re-binding the
reference.
If you re-write the example in terms of pointers, it is
equivalent to:
```d
void main() {
auto a = 0;
auto b = 0;
const c = 1;
int* ptr = &(c ? a : b);
*ptr = 8;
assert(a == 8);
*ptr = (c ? b : a);
*ptr = 2;
}
```
More information about the Digitalmars-d
mailing list