I want to access the bits in a char
individually. There are several questions and answers on this topic here on SO, but they all suggest to use boolean mathematics. However, for my use it would be more convenient if I could simply name the bits separately. So I was thinking of just accessing the char
through a bitfield, like so
#include <stdbool.h>
#include <stdio.h>
typedef struct {
bool _1 : 1, _2 : 1, _3 : 1, _4 : 1, _5 : 1, _6 : 1, _7 : 1, _8 : 1;
} bits;
int main() {
char c = 0;
bits *b = (bits *)&c;
b->_3 = 1;
printf("%s\n", c & 0x4 ? "true" : "false");
}
This compiles without errors or warnings with gcc -Wall -Wextra -Wpedantic test.c
. When running the resulting executable with valgrind
it reports no memory faults. The assembly generated for the b->_3 = 1;
assignment is or eax, 4
which is sound.
Questions
- Is this defined behaviour in C?
- Is this defined behaviour in C++?
N.B.: I'm aware that it might cause trouble for mixed endianness but I only have little endian.