C++ Logo

sg12

Advanced search

Re: [ub] Signed shifting

From: Jens Maurer <Jens.Maurer_at_[hidden]>
Date: Tue, 18 Nov 2014 10:04:24 +0100
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

Received on 2014-11-18 10:04:27