C++ Logo

sg12

Advanced search

Re: [ub] Signed shifting

From: Hubert Tong <hubert.reinterpretcast_at_[hidden]>
Date: Tue, 18 Nov 2014 08:36:35 -0500
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:

for (int x = y; x < y + 32; ++x) f[x] += x;

to (possibly)

f[y] += y;
f[y + 1] += y + 1;
...
f[y + 31] += y + 31;

where the original loop might not have performed a single iteration if
wraparound is to reliably occur.

-- HT


On Tue, Nov 18, 2014 at 4:04 AM, Jens Maurer <Jens.Maurer_at_[hidden]> wrote:

> On 11/18/2014 12:14 AM, Howard Hinnant wrote:
> > int
> > sign(int x)
> > {
> > constexpr int n = std::numeric_limits<int>::digits;
> > return (x >> n) | (static_cast<unsigned>(-x) >> n);
> > }
>
> That "-x" in there seems to cause undefined behavior on
> two's complement machines if "x" is std::numeric_limits<int>::min(),
> according to 5p4, it seems:
>
> "If during the evaluation of an expression, the result is [...] not
> in the range of representable values for its type, the behavior is
> undefined."
>
>
> Can we make the world a simpler and better place by prescribing two's
> complement for all signed integer operations in C++, thereby enshrining
> what everybody expects, anyway?
>
> Jens
>
> _______________________________________________
> ub mailing list
> ub_at_[hidden]
> http://www.open-std.org/mailman/listinfo/ub
>

Received on 2014-11-18 14:36:36