I asked AI (Claude), and it told me it is UB. Is that real?
#include <stdio.h>
struct BitFieldStruct {
unsigned int a : 5;
unsigned int : 3; // 3位填充位
unsigned int b : 6;
unsigned int c : 10;
};
int main() {
struct BitFieldStruct s1 = {10, 20, 300};
struct BitFieldStruct s2;
printf("s1.a = %d, s1.b = %d, s1.c = %d\n", s1.a, s1.b, s1.c);
s2 = s1; // UB
printf("s2.a = %d, s2.b = %d, s2.c = %d\n", s2.a, s2.b, s2.c);
// may not same as s1
return 0;
}
I searched the internet and was still confused.
Claude told me that it is according C99(6.7.2.1.14). I think Claude read it wrong. But English is not my native language. I am not sure I read it right.
When a value is stored in an object of structure or union type, including a case as part of a value of a union type, the bytes of the object representation shall be written in order with the values of the members given in increasing bit-field order, with implementation-defined behavior in the case of an overlap. The order for byte components is implementation-defined. The values of members that are unions are stored according to the union definition.
When a value is stored in a bit-field of an object of a structure or union type, the value shall be represented with an integer type and the encoding defined by ANSI/IEEE Std 754-1985. The value shall be stored in the minimum number of bits needed to represent the value and the integral part of the value, if any, shall occupy the least significant bit position(s).
When a value in a bit-field is read, its value shall be represented with an integer type and the encoding defined by ANSI/IEEE Std 754-1985. If insufficient memory remains, whether or not the entire bit-field can be read, the value shall be read as an unsigned integer and the value of the entire bit-field becomes an indeterminate value.
The behavior is undefined in the following cases:
**When storage is accessed by an lvalue that does not designate an object of a structure or union type compatible with the effective type of the lvalue.
When a value is stored into or read from a bit-field of an object in a different order than the order of allocation of the components of the value having an integer type.**