Quiz Entry - updated: 2026.07.10
What is short-circuit evaluation and why is p && *p a common pattern?
&& and || stop evaluating the moment the result is decided, so p && *p safely tests p first and only dereferences it when it's non-NULL.
How it works:
&&(AND): If left side is false, right side is never evaluated||(OR): If left side is true, right side is never evaluated
Why? Because the result is already determined:
false && anything → false (no need to check 'anything')
true || anything → true (no need to check 'anything')
The p && *p pattern - safe pointer dereferencing:
// If p is NULL, *p would crash. But this is SAFE:
if (p && *p) {
// Only reaches here if p is non-NULL AND *p is non-zero
}
// Because:
// 1. First checks: p != NULL?
// 2. If p is NULL (false), stops immediately - never dereferences!
// 3. Only if p is valid does it check *p
Logical operators always return 0 or 1:
// !nonzero = 0
!0x41 → 0x00
// !zero = 1
!0x00 → 0x01
// Double negation normalizes to 0 or 1
!!0x41 → 0x01
// Both non-zero = true
0x69 && 0x55 → 0x01
// At least one non-zero = true
0x69 || 0x55 → 0x01
Contrast with bitwise operators:
// Bitwise & and | evaluate BOTH sides and operate on bits:
// Bitwise AND
0x69 & 0x55 → 0x41
// Bitwise OR
0x69 | 0x55 → 0x7D
Go deeper:
Short-circuit evaluation — Wikipedia — how && and || stop early, and why it is safe.