问题
Suppose I have a structure defined as follows:
typedef struct Counters {
uint8_t counterSec : 6;
uint8_t : 3;
uint8_t counterMin : 6;
uint8_t : 3;
uint8_t counterHr : 5;
uint8_t : 1;
};
As I want to dedicate 6 bits per first two counters and 5 bits per last counter, I end up with 17 bits, which means that a total of 24 bits will be allocated to an instance of Counters-type structure variable. What may be a practical significance of defining empty bit fields such as in the structure above - if there is any?
In response to the duplicity of this question - a similar question has indeed been asked before. The situation in which I encountered empty bit fields relates to microcontroller programming and configuring registers - hence, the question is regarding the use of empty bit fields in that particular situation. Unfortunately, answers on a similar post did not address these question. Hopefully this will justify this question a little bit more :)
回答1:
There are a number of reasons you might see an empty bit field. They might be reserved for some future use, such as expanding the existing fields without having to change their offsets. They may also be there for alignment purposes, padding out to some nice "round" alignment. In structures that get passed to/from hardware registers, you can see empty bit fields because the hardware will mandate the exact bit layout of the structure. Whatever their purpose is, giving the fields a meaningful name will help indicate their purpose.
As a side note, your structure looks a bit off. You are using an 8-bit data type but your fields don't align to any particular boundary. Either change your 3-bit reserved space to 2 bits (so that each pair of fields fits in a uint8_t
) or use a single data type like uint32_t
that can hold all of your fields in one.
来源:https://stackoverflow.com/questions/35075688/purpose-of-empty-bit-fields-in-a-structure