There are many cases where it would be useful to perform integer operations directly on small unsigned integer types. Because the behavior of ushort1 = ushort1+intVal; in all certain cases it will be tantamount to forcing intVal to type ushort1 , and then performing the addition directly on this type, however, the authors of the Standard did not need to write special rules for this situation. I think they clearly realized that this behavior was useful, but they expected implementations to behave as a rule, regardless of whether the standard authorized it.
By the way, gcc sometimes handles arithmetic for values โโof type uint16_t differently when the result is forced to uint16_t than when it is not. For example, given
uint32_t multest1(uint16_t x, uint16_t y) { x*=y; return x; } uint32_t multest2(uint16_t x, uint16_t y) { return (x*y) & 65535u; }
The multest1() function, apparently, in all cases sequentially modifies the 65536 mod, but the multest2 function does not. For example, the function:
void tester(uint16_t n, uint16_t *p) { n|=0x8000; for (uint16_t i=0x8000; i<n; i++) *p++= multest2(65535,i); return 0; }
will be optimized equivalently:
void tester(uint16_t n, uint16_t *p) { n|=0x8000; if (n != 0x8000) *p++= 0x8000; return 0; }
but this simplification will not happen when using multest1 . I would not consider the behavior of gcc mod-65536 reliable, but the difference in code generation shows that:
Some compilers, including gcc, do the mod 65536 arithmetic directly when the result is forcibly applied to uint16_t, but ...
Some compilers handle integer overflows in ways that can cause erroneous behavior, even if the code completely ignores all the upper bits of the result, so a compiler that tries to warn about all possible UBs must specify constructs whose compilers are allowed to handle stupidly as mobility violations.
Although there are many operators of the form ushort1 + = intval that cannot cause overflow, it is easier to curse with all such statements than to identify only those that can cause erroneous behavior.
supercat Nov 21 '17 at 16:52 2017-11-21 16:52
source share