gotchaModeratepending
Off-by-one errors — fencepost problem in loops and ranges
Viewed 0 times
off-by-onefencepostboundaryinclusive exclusivearray boundspagination skip
nodejspythonbrowser
Error Messages
Problem
Loop processes one too many or one too few items. Array index out of bounds on the last iteration. Range excludes the boundary value that should be included. Pagination skips or duplicates items.
Solution
(1) Count the inputs: for a fence with N sections, you need N+1 posts. (2) Use exclusive end ranges consistently: [start, end) is the convention in most languages (Python range(), JS slice(), SQL OFFSET/LIMIT). (3) Loop invariant: write what's true before and after each iteration. (4) Test boundaries: empty input, single item, first item, last item. (5) Pagination: use cursor-based (after=lastId) instead of offset-based (OFFSET 10) to avoid skipping/duplicating when data changes. (6) Array iteration: for (let i = 0; i < arr.length; i++) — note < not <=. (7) String slicing: str.substring(0, 5) returns chars 0-4 (5 chars), not 0-5.
Why
Off-by-one is the most common bug in programming because humans think in terms of inclusive ranges (1 to 10 = 10 items) while most APIs use half-open ranges (0 to 10 = indices 0-9).
Revisions (0)
No revisions yet.