0
#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?

Jichao
  • 40,341
  • 47
  • 125
  • 198

2 Answers2

3

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.

hobbs
  • 223,387
  • 19
  • 210
  • 288
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.

Amit Chauhan
  • 6,151
  • 2
  • 24
  • 37