c union and bitfields

2019-02-12 18:07发布

Can bitfields be used in union?

4条回答
仙女界的扛把子
2楼-- · 2019-02-12 18:14

If you think about how union works, you have the answer, which is yes, of course (why not)? As we expect, the union is big enough to hold the largest datum, and so automatically the smaller. Bitfields are packed into "containers" and the compiler must be able to evaluate their final real size. The following shows some interesting facts (and of course is a wrong usage of a union, but not for the bitfield presence!)

#include <stdio.h>

union test {
  int a:5;
  int b:12;
  float c;
  double d;
  int x;
};

int main()
{
  union test x;
  printf("%d\n", sizeof(x));
  x.a = 31;
  printf("%d\n", x.a);
  printf("%d\n", x.b);
  x.c = 1.23;
  printf("%d\n", x.a);
  printf("%f\n", x.c);
  x.x = 31;
  printf("%d\n", x.x);
  printf("%d\n", x.a);
  printf("%d\n", x.b);
}
查看更多
迷人小祖宗
3楼-- · 2019-02-12 18:15

It's only unsafe if you write to one union element and read from a different one. If the details of your implementation ensure that does not happen, then a union containing a bitfied (and presumably other members) has well defined, safe behavior.

查看更多
▲ chillily
4楼-- · 2019-02-12 18:19

Yes, they can be. Why not? Bit-fields in unions behave in the same way they behave anywhere else. There's nothing special about bit-fields in unions (or unions with bit-fields).

查看更多
Viruses.
5楼-- · 2019-02-12 18:25

Yes it is possible, but I would recommend against it. The length and packing of bitfields is not portable. The size of the union will be difficult to predict (see here). There is a certain amount of complexity that you introduce into the code when you use unions or bitfields. While this complexity may be acceptable in your code, combining the two may result in an unacceptable amount of complexity. If you are using unions, structs and bitfields, you run into problems with memory alignment.

If this is throwaway code that only needs to be built and run on one machine, then it's probably fine. However, if you are checking this into version control where it will live on forever, I recommend against it.

If you give an example of why you want to do this, I or someone else can suggest a better alternative.

EDIT: clarified based on comments and to ask for feedback.

查看更多
登录 后发表回答