开发者

c union and bitfields

Can bitfields b开发者_如何学编程e used in union?


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).


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.


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);
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜