-1
struct mybitfields
{
    unsigned short a : 4;
    unsigned short b : 5;
    unsigned short c : 7;
} test;

Why is the : used instead of =. I'm really confused.

  • It's called a bit-field: http://en.wikipedia.org/wiki/Bit_field – jrd1 Apr 09 '15 at 05:03
  • 1
    It's a bit-field. In the case of `a : 4`, it means 4 bits are used for `a`, meaning `a` can only store small values, specifically `0-15`. The advantage is its very small. But how exactly the bits are stored is up to the compiler. – VoidStar Apr 09 '15 at 05:03
  • @VoidStar how's this different than a union? – Celeritas Apr 09 '15 at 05:29
  • 1
    @Celeritas: In a union, `a`, `b`, and `c` would be overlapped, providing views to the same memory; for example, setting `a` would also set `c`. In a bit field, `a`, `b`, and `c` are usable as separate values. They are just packed really close together. – VoidStar Apr 09 '15 at 06:44
  • @VoidStar right I see they are quite different, though bit-fields seem really useless as memory isn't bit addressable: at best it's byte addressable. Assuming 8 bit bytes `a` and `b` still take 2 bytes... – Celeritas Apr 09 '15 at 07:47
  • @Celeritas: Addressing doesn't matter, you can't even take the address of a bit field anyway. If you created say, eight 1-bit bit fields, the compiler might decide to pack them all into a single byte in memory, using bitwise operators (under the covers) to get/set the individual bits. It will pack them however it thinks is smallest and best-aligned. – VoidStar Apr 09 '15 at 08:54

1 Answers1

2

This is bit fields and it is used to specify that struct members occupies exactly given number of bits.

In your example it is 4 bits for test.a, 5 for test.b and 7 bits for test.c.

This is useful for typecasting for example. You can have short variable that can be cast to test and get exactly needed bits.

Read this for more information.