char and the usual arithmetic conversion rules

后端 未结 5 871
一向
一向 2020-12-10 17:00

I know this question has been asked and seemingly answered a gazillion times over but I can\'t seem to match the answers to my own experience.

The C standard specifi

5条回答
  •  粉色の甜心
    2020-12-10 17:30

    I think there is no contradiction here. The compiler is not obliged to follow any specific computation path as long as the observable result is as if it would follow the prescribed way.

    In particular, for your case, if we would do the computation with promotion to int (say, to 16 bit): a promoted to int has the same value, so does b as well. The value of a + b is actually (a + b) mod 2^16, but we assign this to an unsigned char, which is truncating the upper 8 bits, that is the same as taking the result mod 2^8: ((a + b) mod 2^16) mod 2^8 = (a + b) mod 2^8.

    The calculation without integer promotion would result in (a + b) mod 2^8, which is exactly the same.

提交回复
热议问题