<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 &lt; 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">&lt;<a href="mailto:Jens.Maurer@gmx.net" target="_blank">Jens.Maurer@gmx.net</a>&gt;</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>
&gt; int<br>
&gt; sign(int x)<br>
&gt; {<br>
&gt;     constexpr int n = std::numeric_limits&lt;int&gt;::digits;<br>
&gt;     return (x &gt;&gt; n) | (static_cast&lt;unsigned&gt;(-x) &gt;&gt; n);<br>
&gt; }<br>
<br>
</span>That &quot;-x&quot; in there seems to cause undefined behavior on<br>
two&#39;s complement machines if &quot;x&quot; is std::numeric_limits&lt;int&gt;::min(),<br>
according to 5p4, it seems:<br>
<br>
&quot;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.&quot;<br>
<br>
<br>
Can we make the world a simpler and better place by prescribing two&#39;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>