Skip to content
BENIBIX Learn

Off-by-One Error

Development🧩 Programming ConceptsErrors

Also known as Off by One, OBOE, Fencepost Error

A loop or count that goes one step too far or stops one step short.

Think of it like

It is like posts in a fence. Ten gaps need eleven posts, and people often say ten.

Example

Jack's loop runs while i <= 5 over a list of 5 names. It reaches index 5, which does not exist, and the app crashes.

Why it matters

It is one of the most common bugs in all of coding. It hides at the edges, so a quick test of the middle misses it.

Definition

An off-by-one error is a count or a loop that goes one step too far or stops one step short. It often comes from starting at 0 or 1, or from mixing up less than and less than or equal to. Lists in most languages start at index 0, so the last item of 5 is at index 4. Reading index 5 goes past the end.

Example code

python
names = ["Ana", "Ben", "Cy", "Di", "Ed"]
for i in range(5):
    print(names[i])   # 0 to 4, right
print(names[5])       # IndexError
range(5) gives 0 to 4. Index 5 is one past the end.
Five items sit at 0 to 4. A loop that reaches 5 has gone one too far.

Common mistake

Testing only with a typical list. Try an empty list, one item and the very last item.

Key takeaways

  1. 1
    Edges matter. The first and last steps go wrong.
  2. 2
    Zero-based count. Five items end at index 4.
  3. 3
    Check < and <=. One sign moves the end by one.

Learn it properly