C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Reduce undefined behavior of signed integer literal arithmetic operations

From: Julien Villemure-Fréchette <julien.villemure_at_[hidden]>
Date: Thu, 27 Apr 2023 16:55:24 -0400
Doesn't work that way. Signed arithmetic overflow is UB to permit compilers to transform, for instance
```
auto a = -(-b);
// to...
auto a = b;
```
For all values of `b` for which the expression `-(-b)` is well defined.

You propose we should let compile time evaluations evaluate with semantics which are different from runtime... That's DOA.

If you want to promote your calculations, just ask for it:
```
auto a = INT_MAX +1L;
auto b = 0L -INT_MIN;
```

Btw, compile time UB (at least, signed overflow) cannot happen. A conforming implementation must diagnose.

On April 27, 2023 3:56:28 p.m. EDT, Jonathan Wakely via Std-Proposals <std-proposals_at_[hidden]> wrote:
>On Thu, 27 Apr 2023 at 20:35, 萧 叶轩 via Std-Proposals <
>std-proposals_at_[hidden]> wrote:
>
>>
>>
>> Reduce undefined behavior of signed integer literal arithmetic operations
>>
>>
>>
>> Abstract
>>
>>
>>
>> Apply integral promotion on signed integer literal arithmetic operations
>> to reduce undefined behavior.
>> Background
>>
>> According to:
>>
>> basic.fundamental/1 <http://eel.is/c++draft/basic.fundamental#1> : The
>> range of representable values for a signed integer type is −2<sup>N−1</sup>
>> to 2<sup>N−1</sup> − 1.
>>
>> basic.fundamental/2 <http://eel.is/c++draft/basic.fundamental#2> :
>> Overflow for signed arithmetic yields undefined behavior.
>>
>> expr.pre/4 <http://eel.is/c++draft/expr.pre#4> : If during the evaluation
>> of an expression, the result is not mathematically defined or not in the
>> range of representable values for its type, the behavior is undefined.
>>
>> Considering the following code, each line has an undefined behavior:
>>
>>
>>
>> auto a = INT_MAX + 1;
>>
>> auto b = -INT_MIN;
>>
>> long long c = INT_MAX + 1;
>>
>> long long d = -INT_MIN;
>>
>>
>>
>> GCC and Clang can diagnose that `INT_MAX + 1` and `-INT_MIN` have
>> undefined behavior, while MSVC can only diagnose that `INT_MAX + 1` has.
>> Solution
>>
>> Add a rule that when the operands of an operator are literals, apply
>> integer promotion to increase the width of the type of the result to be
>> large enough to store the value of the result value.
>>
>
>INT_MIN is not required to be a literal though, it might be something like
>(-INT_MAX - 1). That's an integral constant expression of type int. So the
>operand of -INT_MIN is not a literal.
>
>None of the constants in <limits.h> are required to be literals, so INT_MAX
>might be something like (2147483647), which also isn't a literal.

Received on 2023-04-27 20:55:39