Understanding the Behavior of i + ++i in D Language

Nick Treleaven nick at geany.org
Fri Aug 23 09:42:38 UTC 2024


On Friday, 23 August 2024 at 08:58:16 UTC, Me'vâ wrote:
> ```
> import std.stdio:writeln;
>
> void main() {
>     int i = 5;
>     writeln("Result: ", i + ++i);
> }
> ```
>
> When I run this, it surprisingly outputs 11. I tried something 
> similar in C before and it gave me 12. I’m curious, why is 
> there a difference? How is i + ++i evaluated in D that it ends 
> up giving 11 instead of 12?

D: `5 + 6`
C++: undefined, could be `6 + 6` if the increment is done first. 
g++ gives me a warning with `-Wall`:

```
inc.cxx: In function ‘int main()’:
inc.cxx:30:26: warning: operation on ‘i’ may be undefined 
[-Wsequence-point]
    30 |         std::cout << i + ++i << "\n";
       |                          ^~~
```

> Is there something about operator precedence or evaluation 
> order in D that I'm missing? I'd really appreciate it if 
> someone could break it down for me or point me towards some 
> resources to get a better understanding of what's going on.

See https://dlang.org/spec/expression.html#order-of-evaluation

> Binary expressions except for AssignExpression, OrOrExpression, 
> and AndAndExpression are evaluated in lexical order 
> (left-to-right).

So in D, the value of `i` on the left is always read before the 
increment on the right.


More information about the Digitalmars-d-learn mailing list