<div dir="ltr"><div>UB for signed integer overflow is often relied on by optimizers to either increment 32-bit ints in 64-bit registers on RISC systems without enforcing exact wraparound or to perform loop optimizations:</div><div> </div><div>for (int x = y; x < y + 32; ++x) f[x] += x;</div><div> </div><div>to (possibly)</div><div> </div><div>f[y] += y;<br>f[y + 1] += y + 1;<br>...<br>f[y + 31] += y + 31;</div><div> </div><div>where the original loop might not have performed a single iteration if wraparound is to reliably occur.</div><div> </div><div>-- HT</div><div> </div></div><div class="gmail_extra"><br><div class="gmail_quote">On Tue, Nov 18, 2014 at 4:04 AM, Jens Maurer <span dir="ltr"><<a href="mailto:Jens.Maurer@gmx.net" target="_blank">Jens.Maurer@gmx.net</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span>On 11/18/2014 12:14 AM, Howard Hinnant wrote:<br>
> int<br>
> sign(int x)<br>
> {<br>
> constexpr int n = std::numeric_limits<int>::digits;<br>
> return (x >> n) | (static_cast<unsigned>(-x) >> n);<br>
> }<br>
<br>
</span>That "-x" in there seems to cause undefined behavior on<br>
two's complement machines if "x" is std::numeric_limits<int>::min(),<br>
according to 5p4, it seems:<br>
<br>
"If during the evaluation of an expression, the result is [...] not<br>
in the range of representable values for its type, the behavior is<br>
undefined."<br>
<br>
<br>
Can we make the world a simpler and better place by prescribing two's<br>
complement for all signed integer operations in C++, thereby enshrining<br>
what everybody expects, anyway?<br>
<span class="HOEnZb"><font color="#888888"><br>
Jens<br>
</font></span><div class="HOEnZb"><div class="h5"><br>
_______________________________________________<br>
ub mailing list<br>
<a href="mailto:ub@isocpp.open-std.org">ub@isocpp.open-std.org</a><br>
<a href="http://www.open-std.org/mailman/listinfo/ub" target="_blank">http://www.open-std.org/mailman/listinfo/ub</a><br>
</div></div></blockquote></div><br></div>