cstruct

What is meaning of ":" in struct C


  struct Test
  {
      unsigned a : 5;
      unsigned b : 2;
      unsigned c : 1;
      unsigned d : 5;
  };
  
  Test B;
  printf("%u %u %u %u", B.a, B.b, B.c, B.d); // output: 0 0 0 0
  static struct   Test A = { 1, 2, 3, 4};

Could someone explain me what is purpose of : in struct, printf just outputs 0 so I assume these are not default values, but what they are then?

Also could someone explain me why does A.a, A.b, A.c, A.d outputs 1, 2, 1, 4 instead of 1, 2, 3, 4


Solution

  • That is a bit field.

    It basically tells the compiler that hey, this variable only needs to be x bits wide, so pack the rest of the fields in accordingly, OK?