<< operator in C is the bitwise left shift operator. It operates on integral types by shifting the binary representation of the promoted left operand to the left by the number of bit positions specified by the right operand.
Integer Promotion and Mechanics
Before the shift operation occurs, C applies integer promotions to both operands independently. Types smaller thanint (such as char, short, or uint8_t) are promoted to int (or unsigned int if int cannot represent all values of the original type). The shift operation is performed strictly on the promoted type of the left operand.
When a left shift is executed at the bit level:
- The bits of the promoted left operand are moved to the left.
- The vacated Least Significant Bits (LSB) are filled with zeros.
- The bits that are shifted beyond the bit-width of the promoted type (Most Significant Bits, or MSB) are discarded.
Result Type
The type of the evaluated result is strictly the type of the promoted left operand. The type and value of the right operand have no effect on the type of the result.Mathematical Equivalence
For an expressionE1 << E2, the operation is mathematically equivalent to multiplying the promoted E1 by , provided that the resulting value can be perfectly represented in the promoted type of E1 without overflow.
Undefined Behavior (UB)
The C standard imposes strict constraints on the<< operator. Violating these constraints results in Undefined Behavior:
- Negative Shift Count: If the right operand (
E2) is less than zero. - Oversized Shift Count: If the right operand (
E2) is greater than or equal to the width (in bits) of the promoted left operand. - Negative Left Operand (Signed): If the promoted left operand has a signed type and a negative value.
- Signed Overflow: If the promoted left operand has a signed type and a non-negative value, but the mathematical result of cannot be represented in the promoted result type.
Well-Defined Unsigned Overflow
If the promoted type of the left operand is unsigned, overflow is well-defined. The result is mathematically reduced modulo , where is the bit-width of the promoted left operand. Note: This wrap-around guarantee only applies if the promoted type is unsigned. If an unsigned type (likeunsigned char or uint8_t) promotes to a signed int, overflowing that signed int during the shift remains Undefined Behavior.
Tired of Poor C Skills? Fix That With Deep Grasping!Learn More





