Compound bitwise assignments
What you'll learn: How to use shorthand operators to modify a variable's binary bits in a single step.
The shorthand for bit manipulation
In C, we often need to update a variable by performing a bitwise operation on its current value. For example, if you want to turn on a specific bit (using OR) or mask out certain bits (using AND), you might write x = x | 5;.
Just like you can use += as a shortcut for addition, C provides compound bitwise assignment operators. These combine a bitwise operator (&, |, ^, <<, >>) with the assignment operator (=). Instead of writing the variable name twice, you merge the operation into the equals sign.
Think of it like a light switch panel. If you want to flip a specific switch without touching the others, you don't need to rebuild the whole panel; you just apply the change directly to the existing state.
Common compound operators
Here are the most frequently used bitwise shortcuts:
&=(Bitwise AND assignment): Useful for clearing specific bits.|=(Bitwise OR assignment): Useful for setting (turning on) specific bits.^=(Bitwise XOR assignment): Useful for toggling (flipping) bits.<<=and>>=(Shift assignments): Moves all bits to the left or right and updates the variable.
Seeing it in action
Imagine we are managing the status of a game character using bits. Each bit represents a status like "Poisoned" or "Shielded."
#include <stdio.h>
int main() {
unsigned char status = 0; // Binary: 0000 0000 (All effects off)
// Set the 1st and 3rd bits (binary 0000 0101, which is 5 in decimal)
// Same as: status = status | 5;
status |= 5;
// Now status is 0000 0101.
// Let's toggle the bits using XOR.
// This flips 0s to 1s and 1s to 0s based on the mask.
status ^= 1; // Flips the last bit
// Finally, shift everything left by 2 positions
// Same as: status = status << 2;
status <<= 2;
return 0;
}
Why use them?
Using status |= mask instead of status = status | mask makes your code cleaner and reduces the chance of typos, especially when your variable names are long (like player_attribute_flags). It signals to anyone reading your code that you are performing an "in-place" modification to the data.
Key takeaway
Compound bitwise operators (&=, |=, ^=, <<=, >>=) provide a concise way to update a variable's binary state without repeating the variable name.