Bitfields Unexpected Output

I have a code that goes like this:

typedef struct _point {
int x:2;
int y:2;
}Point;

int main()
{
Point p;
p.x = 2;
printf("%d\n", p.x);
}

The output produced is -2 but I was expecting a 2. Please help
In 2's compliment, the high bit is negative. Therefore if you have a 2-bit value, its range is [-2..1]. If you want the range to be [0..3], then you must make the variable unsigned:

1
2
unsigned x:2;
unsigned y:2;
Classical sign extension bug.

x can only contain two bits, to which you're assigning binary 10. When you pass p.x to printf(), the value is converted to int and sign extension is applied: 10b becomes 11111111 11111111 11111111 11111110b (assuming 32-bit ints), which in two's complement is -2.
If you want to be able to store 2, either using unsigned instead of int, or give at least three bits to each member.
Topic archived. No new replies allowed.