Overflow in bit fields

后端 未结 4 966
野趣味
野趣味 2021-02-13 04:48

can I trust that the C compiler does modulo 2^n each time I access a bit field? Or is there any compiler/optimisation where a code like the one below would not print out Overflo

4条回答
  •  旧巷少年郎
    2021-02-13 05:18

    Yes, you can trust the C compiler to do the right thing here, as long as the bit field is declared with an unsigned type, which you have with uint8_t. From the C99 standard §6.2.6.1/3:

    Values stored in unsigned bit-fields and objects of type unsigned char shall be represented using a pure binary notation.40)

    From §6.7.2.1/9:

    A bit-field is interpreted as a signed or unsigned integer type consisting of the specified number of bits.104) If the value 0 or 1 is stored into a nonzero-width bit-field of type _Bool, the value of the bit-field shall compare equal to the value stored.

    And from §6.2.5/9 (emphasis mine):

    The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.31) A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

    So yes, you can be sure that any standards-conforming compiler will have G.foo overflow to 0 without any other unwanted side effects.

提交回复
热议问题