nowox nowox - 2 months ago 16x
C Question

How to clear all fields in a bit-field struct, except one?

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

One solution would be:

bool temp =;
*(*long)&bf = 0; = temp;

Is there a proper way that does not require any temporary boolean?


C bitfield-structs 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 = };

to keep .bar and set all other fields to 0.

Note there is another problem with your code: you use signed integers, so siongle bits can (on typical hardware) only hold 0 and -1. Which is not what a bool can hold. Your compiler should warn you about this, if not, enable warnings, e.g. -Wconversion (gcc).


typedef struct {
    bool foo : 1;
} bitfield;

(Mind the the ;s)