Expression evaluation order
bearophile
bearophileHUGS at lycos.com
Fri Jun 14 04:08:09 PDT 2013
monarch_dodra:
> *as* a matter of fact, that's how gcc does it for C++:
>
> //----
> int main()
> {
> int i = 0;
> ++i = ++i;
> assert(i == 2); //passes
> }
> //----
>
> Left to right
> First, evaluate lhs: i has the value 1.
> then evaluate rhs, which will now have the value 2.
> assign 2 to i.
> * i == 2 *
>
> right to left:
> First, evalutate rhs: i has the value 1, an rhs 1.
> Evaluate lhs: i is now 2.
> But then assign rhs (1) to lhs.
> * i == 1 *
>
> So yeah, left to right evaluation is completely coherent, and a
> valid scheme.
I think the results of your code is not defined by the C++
standard, so in practice writing that code is a programmer's
mistake. And it's a mistake to design a modern programming
language that accepts code that gives undefined results.
To be considered a grown up language D needs define only one
semantics, or forbid code like that.
> Evaluation order, even when defined, remains obscure once
> associative operations come into play, and still bite you in
> the ass anyways,
Even when the programmer isn't able to know what the result will
be, it's essential for the D code to give the same result on all
CPUs and on all compilers.
Bye,
bearophile
More information about the Digitalmars-d
mailing list