In C++, why is `len >= 1 && (buf[0] >> 4) == 4` safe on an empty buffer, but not the `&` version?
answer
- left operand decides
- second operand may never run
- sequenced before, side effects included
- bitwise & evaluates both, unsequenced
basics
~20 sBuilt-in && evaluates its left operand first and skips the right one when the left is false, so buf[0] is never read on an empty buffer. Bitwise & evaluates both operands in no fixed order and reads out of bounds.
solid answer
~40 sThe built-in `&&` contextually converts each operand to `bool`, finishes the left operand (value and side effects) before starting the right one, and does not evaluate the right operand at all when the left is `false`; `||` mirrors this and skips the right operand when the left is `true`. That makes `len >= 1 && (buf[0] >> 4) == 4` a guard: `buf[0]` is read only after the length check passed. Bitwise `&` on two `bool`s has the same truth table but always evaluates both operands, unsequenced relative to each other, and yields an `int`. On an empty buffer the `&` version reads past the end, which is undefined behaviour. And an overloaded `operator&&` for a class type is a plain function call, so it never short-circuits.
code
cpp · 21 lines#include <cstddef>
#include <cstdint>
#include <iostream>
// Reads the version nibble only after the length check passed.
bool is_ipv4(const std::uint8_t* buf, std::size_t len) {
return len >= 1 && (buf[0] >> 4) == 4;
}
// Same truth table, but both operands are always evaluated:
// with len == 0 this reads buf[0] anyway (undefined behaviour).
bool is_ipv4_bitwise(const std::uint8_t* buf, std::size_t len) {
return (len >= 1) & ((buf[0] >> 4) == 4);
}
int main() {
const std::uint8_t pkt[] = {0x45, 0x00};
std::cout << is_ipv4(pkt, sizeof pkt) << '\n'; // 1
std::cout << is_ipv4(nullptr, 0) << '\n'; // 0: buf[0] never read
std::cout << is_ipv4_bitwise(pkt, sizeof pkt) << '\n'; // 1, but never call it with len == 0
}go deeper
Recall the rule exactly: && stops at the first false, || at the first true, and the left side always finishes first.
Explain sequenced-before for && and contrast it with &: both operands evaluated, unsequenced, and an int result after promotion.
Show where the guarantee is load-bearing in real parsers and where a side effect hidden in the right operand silently stops running.
Treat & in place of && in a guard as a review-blocking defect, and keep overloaded && and || out of shared libraries because they lose short-circuiting.
## What the built-in `&&` and `||` promise The **logical AND** (`&&`) and **logical OR** (`||`) operators are two of the operators whose evaluation order C++ has always fixed. For the built-in versions, the draft's wording in the expressions clause says: - each operand is **contextually converted to `bool`** (the same conversion an `if` condition performs, so an `explicit operator bool` is allowed); - `&&` evaluates its first operand, and **does not evaluate the second at all** when the first is `false`; `||` skips the second operand when the first is `true`; - when the second operand is evaluated, the first is **sequenced before** it: every value computation *and every side effect* of the left operand is complete before the right operand starts; - the result is a `bool`. That combination is called **short-circuit evaluation**. It is a guarantee, not an optimization the compiler may or may not apply, which is why code is allowed to depend on it. ## The guard idiom in a header parser A parser for a bit-packed network header routinely checks that enough bytes arrived before it reads a field: ```cpp bool is_ipv4(const std::uint8_t* buf, std::size_t len) { return len >= 1 && (buf[0] >> 4) == 4; // buf[0] read only if len >= 1 } ``` The left operand is the **guard**: when `len` is `0`, `buf` may be a null pointer or point at an empty array, and `buf[0]` must not be evaluated. Because `&&` never evaluates its right operand after a `false` left operand, the read cannot happen. Longer chains work the same way: `a && b && c` groups as `(a && b) && c`, so each test runs only if every test to its left passed, which is how a parser can check the length, then the version nibble, then a flag bit, each step relying on the one before. ## Why `&` and `|` are not substitutes The bitwise operators `&` and `|` produce the same truth table on `bool` operands, which tempts people to write them for "branch-free" code. They differ in three ways that matter: | | `a && b` | `a & b` (both `bool`) | |---|---|---| | right operand evaluated | only if `a` is `true` | always | | order of the operands | `a` sequenced before `b` | unsequenced | | result type | `bool` | `int` (both operands promoted) | So `(len >= 1) & ((buf[0] >> 4) == 4)` reads `buf[0]` even when `len` is `0`. Reading past the end of an array, or through a null pointer, is **undefined behaviour**: the program has no defined output, whatever a test run happens to print. The `int` result type is a smaller trap: it converts back to `bool` silently in an `if`, but it changes overload resolution and `auto` deduction. ## `?:`, the comma operator and precedence Short-circuiting has relatives: - the **conditional operator** `c ? x : y` evaluates `c` first and then exactly one of `x` and `y`; - the built-in **comma operator** `a, b` evaluates `a` completely, discards it, then evaluates `b`; - `&&` binds tighter than `||`, so `p && p->ready || retry()` means `(p && p->ready) || retry()`; Clang warns about this mix with `-Wlogical-op-parentheses`, and parentheses make the intent explicit. ## Overloaded `&&`, `||` and `,` When an operand has class type and a user-declared `operator&&` is chosen, `a && b` becomes an ordinary function call, `operator&&(a, b)`. Both arguments are evaluated before the call, so **nothing short-circuits**. Since C++17 the operands of an overloaded operator are at least sequenced in the order the built-in operator prescribes (left before right), but the skip is gone. This is the main reason style guides discourage overloading these three operators; how to design operator overloads is covered in the material on overloaded operators. ## Pitfalls to name in an interview 1. Writing `&` for `&&` on `bool`s in a guard: the right operand still runs, and an out-of-bounds read becomes undefined behaviour. 2. Putting a side effect you always need (logging, a counter, a `next()` on a cursor) in the right operand of `&&`: it silently does not run when the left operand is `false`. 3. Assuming the compiler may reorder the operands of `&&` because the right one is cheaper: it may not. 4. Assuming a class type's `operator&&` keeps the built-in short-circuit: it does not.
- Does `a() & b()` call `a()` before `b()` in C++?No order is promised. The operands of the built-in `&` are unsequenced, so a compiler may call `b()` first; the two calls still do not interleave, because function calls are indeterminately sequenced with each other. If the order matters, use `&&` when skipping is acceptable, or call them in separate statements and combine the results.
- What does `p && p->ready || retry()` do when `p` is a null pointer?`&&` binds tighter than `||`, so it parses as `(p && p->ready) || retry()`. With a null `p` the inner `&&` stops after `p`, yields `false`, and `retry()` is then called. Clang flags the mixture with `-Wlogical-op-parentheses`; writing the parentheses states which grouping was meant.
- On bool operands & and && are interchangeable; only speed differs.
- The compiler may evaluate the right operand of && first when it is cheaper.
- A user-declared operator&& short-circuits just like the built-in one.
- Bitwise & on two bool operands produces a bool.
- Short-circuiting skips only the right operand's value; its side effects still happen.