Overflow in bit fields

后端 未结 4 1051
野趣味
野趣味 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:16

    Short answer: yes, you can trust modulo 2^n to happen.

    In your program, G.foo++; is in fact equivalent to G.foo = (unsigned int)G.foo + 1.

    Unsigned int arithmetic always produces 2^(size of unsigned int in bits) results. The two bits of least weight are then stored in G.foo, producing zero.

提交回复
热议问题