Toggle and Clear Individual Flags
Toggle or clear one flag
OR always sets a selected bit. XOR (^) instead flips it: on becomes off, and off becomes on. Positions where the mask has a 0 stay unchanged.
If you need the bit off regardless of its starting state, use flags & ~mask instead. ~ complements every bit of the unsigned mask: the selected 1 becomes 0, and the other zeros become ones. The following AND therefore clears the selected bit while preserving the others. Logical ! is different: it produces a truth value.
#include <stdio.h>
int main(void) {
unsigned int flags = 0x5u; /* 0101 */
unsigned int target = 0x4u; /* 0100 */
flags ^= target; /* 0001 */
printf("Toggled: %u\n", flags);
flags |= target; /* 0101 again */
flags &= ~target; /* 0001 */
printf("Cleared: %u\n", flags);
return 0;
}
The comments show only the low four bits, not the full width of unsigned int. In particular, ~target has ones in every higher position too; AND preserves those positions in flags. ^=, |=, and &= each store their operator's result back in the left-hand variable. Trace the low four bits through each assignment. Toggling a bit twice returns it to where it started; clearing twice still leaves it off. For the exercise, you'll toggle.