-4

This was a code snippet from a test question. The question was what the size of S would be.

struct S
{
    char a : 4;
    unsigned char b : 3;
    signed char : 2;
    char c : 1;
    char d : 5;
};

What does the ":" do? Is there any difference when it is applied to a signed or unsigned char (or any other data type)? When is this usually used?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
black-goat
  • 67
  • 5

1 Answers1

1

It's a bit field, it says that for example char a will only have 4 bits of memory instead of normal 8. Unsigned char b will have only 3 bits of memory. Number of bits limits the range of values it can hold.

Bit Field declares a class data member with explicit size, in bits. Adjacent bit field members may be packed to share and straddle the individual bytes. http://en.cppreference.com/w/cpp/language/bit_field

Izaya
  • 409
  • 3
  • 6