I wrote this code just for the fun of it:
union {
struct {
bool a : 1;
bool b : 1;
bool c : 1;
bool d : 1;
bool e : 1;
bool f : 1;
bool g : 1;
bool h : 1;
} a;
uint8_t b;
} uni {0}; // sets .a bits to false
// union size : 1 byte
I can toggle each bit individually:
uni.a.a = true;
uni.a.d = true;
cout << bitset<8>(uni.b) << endl; // Prints 000010001
And also use bit masks:
uni.b = 0b00001000;
if(uni.a.a) cout << "a";
if(uni.a.b) cout << "b";
if(uni.a.c) cout << "c";
if(uni.a.d) cout << "d";
if(uni.a.e) cout << "e";
if(uni.a.f) cout << "f";
if(uni.a.g) cout << "g";
if(uni.a.h) cout << "h";
// prints 'd'
I know there are other ways to do this (bitwise operations) but I like this design. My question is: is this a good use of bitfields and unions, in terms of reliability and performance?