Shift operator constraints
What you'll learn: How to avoid undefined behavior by staying within the mathematical limits of the left and right shift operators.
The "Overflow" Trap
In C, the bitwise shift operators (<< and >>) feel like magic tricks for multiplying or dividing by powers of two. However, they aren't magic; they are literal instructions to move bits around a finite container. If you try to shift bits further than the container’s width, the C standard stops guaranteeing what will happen. This is known as undefined behavior.
Think of a bitwise shift like sliding a row of physical coins on a small tray. If you have a tray that holds exactly 8 coins and you try to slide the entire row 10 spaces to the right, the coins don't just disappear—the tray itself might tip over, or the behavior becomes unpredictable. In C, if you have a 32-bit integer, you must never attempt to shift it by 32 or more positions.
Two Rules to Remember
To keep your code safe and predictable, you must follow these two constraints:
- Don't shift by the width (or more): If your variable type is 32 bits wide, shifting by 32, 40, or 100 is illegal. The shift amount must be at least 0 and strictly less than the number of bits in the type.
- Don't shift by negative numbers: While it might seem logical that
x << -1should just bex >> 1, C does not work this way. Shifting by a negative amount is undefined and will likely crash your logic or cause a CPU error.
Seeing the Limits in Code
Here is how these constraints look in practice. Notice how we must be mindful of the underlying data type's size.
#include <stdio.h>
int main() {
unsigned int value = 1; // Usually 32 bits
// SAFE: Shifting within the bounds
unsigned int safe_shift = value << 31;
// DANGER: The following are undefined behavior!
// int bad_1 = value << 32; // Shift amount equals bit-width
// int bad_2 = value << -1; // Negative shift
// int bad_3 = value >> 64; // Shift amount exceeds bit-width
printf("Safe shift result: %u\n", safe_shift);
return 0;
}
If you need to shift a value by a large amount, you must use a larger data type (like long long) or perform the shift in multiple, smaller steps. Always ensure your "slider" stays on the "tray."
Key takeaway
Never shift a value by a negative amount or by a number equal to or greater than the total bit-width of the data type.