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

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Aug 29 00:01:16 UTC 2024


On Wednesday, August 28, 2024 3:44:59 PM MDT Johann Lermer via Digitalmars-d-
learn wrote:
> On Friday, 23 August 2024 at 08:58:16 UTC, Me'vâ wrote:
> >     writeln("Result: ", i + ++i);
>
> I would definitely expect 11 as result (but I still have K&R on
> my book shelf, maybe I'm a bit biased). So, when you get 12 with
> C, I would consider that an error.

The order of evaluation is unspecified in C code (C often fails to specify
such things in order to allow the compiler to do whatever would be the most
efficient). So, either answer would be perfectly valid coming from a C
compiler, and if it were specified in C, D would follow the same rule, since
as a general rule, C code is supposed to be valid D code with the same
behavior, or it isn't valid D code.

In general, D locks down the order of evaluation so that the result is
consistent, but it's arguably best practice to just avoid expressions that
modify a variable while also evaluating that variable in another part of the
expression. It makes the code clearer and avoids any order-of-evaluation
issues which may exist in the language.

- Jonathan M Davis






More information about the Digitalmars-d-learn mailing list