Date: Tue, 18 Nov 2014 14:07:13 +0000
| -----Original Message-----
| From: ub-bounces_at_[hidden] [mailto:ub-bounces_at_[hidden]] On
| Behalf Of Jens Maurer
| Sent: Tuesday, November 18, 2014 1:04 AM
| To: WG21 UB study group
| Subject: Re: [ub] Signed shifting
|
| 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?
The problem here is that optimizers in production compilers have gotten clever with undefined behavior resulting from signed integer arithmetic overflow (even, and especially, on hardware with 2's complement.)
-- Gaby
| From: ub-bounces_at_[hidden] [mailto:ub-bounces_at_[hidden]] On
| Behalf Of Jens Maurer
| Sent: Tuesday, November 18, 2014 1:04 AM
| To: WG21 UB study group
| Subject: Re: [ub] Signed shifting
|
| 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?
The problem here is that optimizers in production compilers have gotten clever with undefined behavior resulting from signed integer arithmetic overflow (even, and especially, on hardware with 2's complement.)
-- Gaby
Received on 2014-11-18 15:07:19