struct Type {
uint8_t var : 3;
};
int main()
{
struct Type bar;
bar.var = 1;
uint8_t baz = bar.var << 5;
}
According to the standard, left shifting more than the width of the left operand type is undefined behavior:
6.5.7 Bitwise shift operators/3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
But what about bit fields? Isn’t it at least eight bits here?
>Solution :
6.5.7.3 The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is greater than or equal to the width of the promoted left operand, the behavior is undefined.
The width of the promoted left operand — the width of an int — is at least 16. 5 is much less than 16.
No undefined behaviour yet.
The spec goes on:
6.5.7.4 The result of
E1 << E2isE1left-shiftedE2bit positions; vacated bits are filled with zeros. IfE1has an unsigned type, the value of the result is E1 × 2E2, reduced modulo one more than the maximum value representable in the result type. IfE1has a signed type and nonnegative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.
The LHS has an unsigned type.
No undefined behaviour yet.
Finally, we have the assignment.
6.5.16.1.2 In simple assignment (
=), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
6.3.1.3.2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.60)
No undefined behaviour there either.