More from C++ Now 2014

Joakim via Digitalmars-d digitalmars-d at puremagic.com
Mon May 19 05:12:50 PDT 2014


On Monday, 19 May 2014 at 09:26:23 UTC, qznc wrote:
> On Monday, 19 May 2014 at 08:20:54 UTC, Namespace wrote:
>> On Sunday, 18 May 2014 at 22:29:04 UTC, bearophile wrote:
>>>> "Undefined Behavior in C++; what is it, and why should I 
>>>> care":
>>>> https://github.com/boostcon/cppnow_presentations_2014/blob/master/files/Undefined-Behavior.pdf?raw=true
>>>> This reminds us to remove as much undefined behavior as 
>>>> possible from D.
>>>
>>> Fixing some of those problems will break some D code. An 
>>> example from the slides pack:
>>>
>>> void main() {
>>>   import std.stdio;
>>>   auto arr = [0, 2, 4, 6, 8];
>>>   int i = 1;
>>>   writeln(i + arr[++i] + arr[i++]);
>>> }
>> dmd is right, so ldc has probably a bug.
>> i is 1
>> ++i is 2 -> arr[2] is 4
>> i++ is still 2 -> arr[2] is 4
>> 1 + 4 + 4 = 9
>
> Addition does not imply an order in D, does it? So, the 
> following lines should be equivalent:
>
> writeln(i + arr[++i] + arr[i++]);
> writeln(arr[++i] + i + arr[i++]);
> writeln(arr[i++] + i + arr[++i]);
> writeln(i + arr[i++] + arr[++i]);
>
> Your reasoning step "is still 2" is inapplicable when there is 
> no order.

Actually, he got that part right.  i++ will always be 2, as it's 
only incremented after the statement is done.  It took me a 
minute to realize how the ldc result was even possible: it's 
because the result depends on whether the pre-increment ++i is 
done before the entire statement is evaluated, so both i and ++i 
are 2, or between evaluating i and arr[++i], so i is 1 and ++i is 
2.  dmd and ldc apparently do the pre-increment at different 
times, hence undefined behavior.


More information about the Digitalmars-d mailing list