Fitzwilliam Bennet-Darcy - 9 months ago 46

C++ Question

I have spent some time trawling this site; in particular this question: Is ((a + (b & 255)) & 255) the same as ((a + b) & 255)?

In doing so, I've been led to the conclusion that

`int main()`

{

unsigned short i = std::numeric_limits<unsigned short>::max();

unsigned short j = i;

auto y = i * j;

}

can lead to undefined behaviour due to a type promotion of

`i`

`j`

`int`

`i`

`j`

`unsigned short`

`int`

Am I correct here?

Answer Source

Yes, it's possible, and your example is likely to be undefined on most desktop architectures.

For the sake of this example, let's assume that `int`

is 32-bit 2's complement type and `unsigned short`

is 16-bit.

I'm using N4140 for the quotes.

Before multiplication, both values are promoted to `int`

:

§ 4.5 [conv.prom] / 1

A prvalue of an integer type other than bool, char16_t, char32_t, or wchar_t whose integer conversion rank (4.13) is less than the rank of int can be converted to a prvalue of type int if int can represent all the values of the source type;

Then:

§ 5 [expr] / 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.

Since the result of 65535 * 65535 (4294836225) is not defined in our 32-bit `int`

(with value range [-2147483648,2147483647]), the behaviour is undefined.