the program is :
typedef struct xp {
int a:2;
int b:2;
int c:1;
} xp;
int main(void)
{
xp x;
memset(&x, 0, sizeof(xp));
x.a = 1;
x.b = 3;
x.c = 1;
printf("%d\n",x.a);
printf("%d\n",x.b);
printf("%d\n",x.c);
return 0;
}
I get 1 -1 -1, why? How are a, b and c stored in x? What happened when printf("%d\n",x.a); is executed?
You're using a signed type for your bitfields, which means you've created what amounts to two two-bit signed integers, and one one-bit signed integer.
The possible values for a two-bit signed integer (two's complement) are: -2, -1, 0, and 1:
The possible values for a one-bit signed integer (two's complement) are -1 and 0.
By storing values that "don't fit", like you have done in these lines:
x.b = 3;
x.c = 1;
You will get strange behaviour as the bit patterns you store are interpreted differently when read. You can have a similar experience by doing something like:
char x = 58147;
on a machine with an 8-bit char
type, that value won't fit, so you'll read something different back when accessing x
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With