[ub] Signed shifting
Jens Maurer
Jens.Maurer at gmx.net
Tue Nov 18 10:04:24 CET 2014
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
More information about the ub
mailing list