Consider the following small program, which uses concatenation to assign integer bits directly, rather than using bit operations. Print statements print correctly, but this does not mean that it will always work.
Is this the correct behavior in C?
#include <stdio.h>
#include <inttypes.h>
union IntBitField{
int32_t foo;
struct bitfield {
unsigned int BIT0:1;
unsigned int BIT1:1;
unsigned int BIT2:1;
unsigned int BIT3:1;
unsigned int BIT4:1;
unsigned int BIT5:1;
unsigned int BIT6:1;
unsigned int BIT7:1;
unsigned int BIT8:1;
unsigned int BIT9:1;
unsigned int BIT10:1;
unsigned int BIT11:1;
unsigned int BIT12:1;
unsigned int BIT13:1;
unsigned int BIT14:1;
unsigned int BIT15:1;
unsigned int BIT16:1;
unsigned int BIT17:1;
unsigned int BIT18:1;
unsigned int BIT19:1;
unsigned int BIT20:1;
unsigned int BIT21:1;
unsigned int BIT22:1;
unsigned int BIT23:1;
unsigned int BIT24:1;
unsigned int BIT25:1;
unsigned int BIT26:1;
unsigned int BIT27:1;
unsigned int BIT28:1;
unsigned int BIT29:1;
unsigned int BIT30:1;
unsigned int BIT31:1;
} bar;
} FooBar;
int main(){
FooBar.foo = 0;
printf("Size of the union: %zu\n", sizeof(union IntBitField));
printf("Before setting any bits %"PRId32"\n", FooBar.foo);
FooBar.bar.BIT31 = 1;
printf("Set BIT31 %"PRId32"\n", FooBar.foo);
}
I reviewed this question and this question , as well as this question , but I'm still not sure.
source
share