Question

#include <iostream>
#include <stdint.h>
struct Foo 
{
    int a : 2;
    int b : 2;
    int c : 2;
    int d : 2;
};
int main()
{
    Foo foo;
    foo.d = 2;
    std::cout << sizeof(foo) << std::endl;
    std::cout << foo.d << std::endl;
    return 0;
}

Using g++, the result turns to be 4 -2, how could foo.d became -2?

Was it helpful?

Solution 2

first one is sign bit. for 2 (10) first one is sign 1 so its negative number. 2's compliment of 10 you will get -2.

OTHER TIPS

int is signed by default, so an int :2 has a range of -2 through 1. Use unsigned int :2 if you want to be able to store values 0 through 3 instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top