opIndexUnary post in-/decrement how to ?

Mike Parker aldacron at gmail.com
Wed Jul 14 14:50:01 UTC 2021


On Wednesday, 14 July 2021 at 12:35:07 UTC, wjoe wrote:
> On Wednesday, 14 July 2021 at 11:31:36 UTC, Tejas wrote:
>>
>> ``` {auto a = i[1] , ++i[1] , a} //note the , not the ;```
>>
>> Sorry I can't provide something even more concrete.
>
> Yes I saw that, and I suppose it would work just fine if it 
> were rewritten to just  ```++i[1]```.
> What I'm struggling to understand is the ```{auto a = i[1], ... 
> ,a}``` part. I can't parse that. What's up with the assignment 
> and the comma stuff ?

It's how the contract of post-inc/dec work---pre-inc/dec return 
the modified value, post-inc/dec return the original value.

```d
int i = 1;
assert(++i == 2);
int j = 1;
assert(j++ == 1);
```
The rewrite of the compiler is done in such a way that the result 
of the expression is the original value. That's what the commas 
are for.

```
So you can parse that rewrite example as it if were a function, 
with each expression separated by a comma, and the final 
expression the result:

```d
int postInc(ref int j)
{
     auto a = j;
     ++j;
     return a;
}
```

It doesn't actually create a function, but this demonstrates the 
effect.

So that's why you don't have to worry about postfix/prefix for 
these. The compiler handles that behind the scenes. All you need 
to worry about is returning the incremented value.


More information about the Digitalmars-d-learn mailing list