What is meaning of “:” in struct C [duplicate]

2019-06-22 09:48发布

问题:

Possible Duplicate:
What does 'unsigned temp:3' means

  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

回答1:

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?



回答2:

These are bit-fields see this Wikipeadia section on Bitfields or this reference about bit fields

The number after the : indicates how many bits you want to reserve for the identifier on the left. This allows you to allocate less space than ordinarily would be the case by tightly packing data. You can only do this in structs or unions.

Here is a short tutorial on bit-fields.



回答3:

Easy explanation: You specify how many bits your variable should be. (You can't specify more bits than the original size of the type.)
EDIT: Your third variable only prints 1 because it has only 1 bit to store its data. So the value can only be 0 or 1. The decimal value 3 is represented by 11 in binary format. So no matter which of the bits gets truncated, you will end up with a 1 stored in your variable.



标签: c struct