Take the following code fragment.
short int a, b = 30001, c = 30002, d = 30003;
a = b + c - d;
Assume that short int is 16 bits and int is 32 bits. Is this undefined behaviour in C++?
My reading of the C standard is that b and c must both be promoted to int, so the entire calculation must be performed using int arithmetic. The final value fits in a short, so UB does not occur.
I cannot find corresponding language in the C++ standard. The section on integer promotion (n3797 S4.5/1) says:
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; otherwise, the source prvalue can be converted to a prvalue of type unsigned int.
The emphasis is mine. Can be is not the same as must be.
S 5/10 says:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
...
— Otherwise, the integral promotions (4.5) shall be performed on both operands. Then the following rules shall be applied to the promoted operands:
— If both operands have the same type, no further conversion is needed.
If the values are not promoted then the consequence is that the intermediate value of the calculation exceeds the range for short int, which means that the answer should be yes, this is UB.
It also means there is an unlikely difference between C and C++. It is not mentioned in the Compatibility section.
All the other questions I could find involved mixtures of types, signed/unsigned, etc. Nothing specifically on this question. It arose in my answer to this.
Any takers?