Definition
A logic error where an index, loop bound, or count includes or excludes an endpoint incorrectly, producing a one‑element discrepancy that can cause wrong results or out‑of‑range accesses.
Principle
Principle
Many algorithms rely on precise boundary conditions (inclusive vs exclusive ranges); a single incorrect ±1 in index arithmetic or loop termination condition changes membership of the set processed and can produce subtle bugs.
Demonstration
Demonstration
A loop written for (i = 0; i <= n; ++i) when the intent was to process n elements indexed 0..n‑1 iterates one extra time, potentially accessing array[n] which is out‑of‑bounds; conversely using < where <= was required misses the last element.
Misapplication
Misapplication
Calling every small off‑by‑one situation trivial or ignoring its security implications; or attributing an algorithmic discrepancy solely to an off‑by‑one when the real issue is an incorrect invariant or off‑by‑two arithmetic elsewhere.
Consequence
Consequence
Correctly reasoning about boundaries eliminates whole classes of indexing and iteration bugs, prevents accidental memory access errors, and yields correct loop invariants; when uncorrected it causes incorrect outputs, exceptions, or vulnerabilities.
Reversal
Reversal
Adopting half‑open interval conventions (start inclusive, end exclusive), using library iterators that carry bounds, or proving loop invariants reverses off‑by‑one mistakes by aligning code with clear boundary semantics.
Boundary
Boundary
Applies where discrete indexing or counting is used (arrays, loops, slices). It excludes higher‑order algorithmic logic errors not reducible to a single unit offset and off‑by‑one is distinct from missing algorithmic cases or threshold misunderstandings.
Semantic Tension
Semantic Tension
Closely related to 'fencepost error' and 'indexing error'; tension arises because some authors treat off‑by‑one as trivial syntactic mistakes whereas in complex algorithms it signals flawed boundary reasoning or invariant design.
Synthesis
Synthesis
An off‑by‑one error is the boundary‑condition mistake that shifts inclusion/exclusion by one unit—grounded in the need for precise index arithmetic—seen in loops and indexing, sometimes dismissed as minor but capable of causing out‑of‑range faults, and best prevented by explicit conventions or formal invariants.