postincrement behaviour (differences between dmd and gdc)
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Wed Jan 24 13:35:01 PST 2007
Nicolai Waniek wrote:
> Hello again,
>
> I have a huge arguing going on with a friend of mine, which behaviour of
> x++ is the right one. This has in fact to do with D, so read on :)
>
> This is our example application:
>
> int x = 5;
> x = x++;
> x = x++;
> print(x);
[snip]
> Allright, now let's look what the compilers do:
>
> C/C++ compiled with GCC: 7
> java compiled with SUN's: 5
> D compiled with DMD: 5
> D compiled with GDC: 7
>
> Allright, so please explain this behaviour to me?
For C & C++, IIRC this is one of the traditional examples of undefined
behavior (although typically with i instead of x, and only one such
statement :p).
The technical reason has to do with sequence points, one of the more
annoying parts of the respective standards.
Basically, the above means the compiler is allowed to emit code that
does either, or even something else entirely. So 42 or 2235023 would be
an equally acceptable answer as 5, 6 or 7 here. (Typically though, since
compilers aren't actively *trying* to screw their users, one of the
latter 3 will result)
I believe D was designed to be as familiar as possible to C programmers
(and therefore, to some degree, those of other C-like languages).
IIRC one guideline to achieve this was that code that looks the same
should have the same behavior. Therefore, this doesn't surprise me at
all. It's in fact exactly what I would expect to happen.
If above reasoning is correct, you can't rely on any particular result;
it's likely to be different between compilers and can even be different
for new versions of the same compiler, or different runs of the same
version of a compiler...
Conclusion: just don't do stupid **** like above code[1].
[1]: That is, in anything other than such short test programs as the
above trying to figure out what the compiler does in such a situation ;)
More information about the Digitalmars-d
mailing list