C++ Logo

sg12

Advanced search

Re: [ub] Signed shifting

From: Gabriel Dos Reis <gdr_at_[hidden]>
Date: Tue, 18 Nov 2014 14:12:22 +0000
See for example, the excellent discussion by Ian in his blog a while back: http://www.airs.com/blog/archives/120

-- Gaby

From: ub-bounces_at_[hidden] [mailto:ub-bounces_at_[hidden]] On Behalf Of Hubert Tong
Sent: Tuesday, November 18, 2014 5:37 AM
To: WG21 UB study group
Subject: Re: [ub] Signed shifting

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]<mailto: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_isocpp.open-std.org<mailto:ub_at_[hidden]>
http://www.open-std.org/mailman/listinfo/ub

Received on 2014-11-18 15:12:27