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

2019-06-22 09:25发布

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

标签: c struct
3条回答
Juvenile、少年°
2楼-- · 2019-06-22 09:57

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?

查看更多
啃猪蹄的小仙女
3楼-- · 2019-06-22 10:01

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.

查看更多
等我变得足够好
4楼-- · 2019-06-22 10:20

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.

查看更多
登录 后发表回答