Can bitfields be used in union?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
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!)
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.
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.