...
Code Block |
---|
struct {
unsigned int a: 8;
} bits = {255};
int main(void) {
printf("unsigned 8-bit field promotes to %s.\n",
(bits.a << 24) < 0 ? "signed" : "unsigned");
}
|
...
The second interpretation is that this is an 8-bit integer. As a result, this eight bit value can be represented as an int
, so integer promotions require that it be converted to int
, and hence "signed". In the signed case, the 24-bit left shift tries to compute 0xFF000000
. For implementations where int is only 32 bits wide, 0xFF000000 > INT_MAX
and the overflow produces undefined behavior (See C99 Sections 3.4.3p3 (non-normative example), 6.5p5 (normative), and 6.5.7p4 (normative)).
The type of the bitfield when used in an expression This also has implications for signed long long
and unsigned long long
types. For example, gcc will also interpret interprets the following as an eight bit value and promote it to int
:
...