I have this definition:
typedef struct {
int foo :1;
int bar :1;
int baz :1;
...
} bitfield;
bitfield bf = {0};
In my code I want to clear the whole bit field without modifying bar
.
One solution would be:
bool temp = bf.bar;
*(*long)&bf = 0;
bf.bar = temp;
Is there a proper way that does not require any temporary boolean?
C bitfield-struct
s are not a good use for single bits. Better use an unsigned int
and shift/masking. This is done in the background anyway. Best use fixed width types, e.g. uint32_t
, etc..
The code in your example invokes undefined behaviour as I stated in a comment already. You violate the effective type (aka strict aliasing) rule. Never use it like this.
However, you can use a compound literal:
bf = (bitfield){ .bar = bf.bar };
to keep .bar
and set all other fields to 0
.
Note there is another problem with your code: you use int
. It is implementation-specific if a a bitfield with int
type is actually signed or unsigned. So each field can either hold 0
and 1
or 0
and -1
on typical implementations. So you leave this to the implementation. _Bool
OTOH is always unsigned with the values 0
and 1
. This is the same as logical operators yield.
Better use boolean fields directly:
typedef struct {
bool foo : 1;
...
} bitfield;
(Mind the the ;
s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With