Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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?

like image 653
nowox Avatar asked Jul 12 '16 07:07

nowox


1 Answers

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

like image 57
too honest for this site Avatar answered Sep 29 '22 23:09

too honest for this site