Why One Ampersand Instead of Two Is a Real Bug
Subtitle: Same look. Different job.
- Left column - Logical AND (&&):
- Works on truth, not bits
- Stops early if left is false
- Right side may never run
- 2 && 4 is true
- For if, while, flow control
- Right column - Bitwise AND (&):
- Works on bits, not truth
- Always runs both sides
- Pairs up the bits, one by one
- 2 & 4 is 0, so false
- For flags, masks, registers
- Simple difference:
- 2 && 4 = true (both non-zero)
- 2 & 4 = 0 (010, 100 share no bit)
Use it when - Logical AND: guards, branches, early exit
Use it when - Bitwise AND: permission masks, device flags
- The test that exposes it - 3 steps:
- if (p != NULL & p->x)
- No short-circuit, so p->x still reads
- Crash. Swap in && and it passes.
Sticky note - Common beginner mistake:
Trusting the compiler to catch it. Both forms are legal and both give a usable condition, so it compiles and ships. Only a side effect on the right side reveals the slip.