c - Overflow in bit fields -


can trust c compiler modulo 2^n each time access bit field? or there compiler/optimisation code 1 below not print out overflow?

struct {   uint8_t foo:2; } g;  g.foo = 3; g.foo++;  if(g.foo == 0) {   printf("overflow\n"); } 

thanks in advance, florian

yes, can trust c compiler right thing here, long bit field declared unsigned type, have uint8_t. c99 standard §6.2.6.1/3:

values stored in unsigned bit-fields , objects of type unsigned char shall represented using pure binary notation.40)

from §6.7.2.1/9:

a bit-field interpreted signed or unsigned integer type consisting of specified number of bits.104) if value 0 or 1 stored nonzero-width bit-field of type _bool, value of bit-field shall compare equal value stored.

and §6.2.5/9 (emphasis mine):

the range of nonnegative values of signed integer type subrange of corresponding unsigned integer type, , representation of same value in each type same.31) a computation involving unsigned operands can never overflow, because result cannot represented resulting unsigned integer type reduced modulo number 1 greater largest value can represented resulting type.

so yes, can sure standards-conforming compiler have g.foo overflow 0 without other unwanted side effects.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -