1

I recently encountered some very strange syntax:

struct Test {
    size_t a : 2;
    size_t b : 3;
    size_t c : 4;
};

Strangely, this compiles with GCC 4.9.2 with all warning flags turned on.

void test_test() {
    Test test;
    std::cout << test.a << " " << test.b << " " << test.c << std::endl;
} 

While declaring test gives no errors and outputs 0 0 0 (I believe 0 is just coincidental; since the struct is Plain Old Data, none of its members are default initialized to 0), changing the declaration to a definition via Test test(); gives the error

tester.cpp:14:20: error: request for member 'a' in 'test', which is of non-class
 type 'Test()'

Enabling C++11 removes the error messages, but the values still remain enigmatically 0. What does this syntax achieve?

LemonPi
  • 1,026
  • 9
  • 22

1 Answers1

7

This syntax is bitfields.

struct Test {
    size_t a : 2; // Occupies two bits
    size_t b : 3; // Occupies three bits
    size_t c : 4; // Occupies four bits
};
WorldSEnder
  • 4,875
  • 2
  • 28
  • 64