## Encyclopedia > Fencepost error

Article Content

# Fencepost error

In computer programming, a fencepost error -- rarely called a "lamp-post error" -- is a computer bug involving the discrete equivalent of a boundary condition[?], often exhibited in programs by iterative loops. This can also occur in a mathematical context, but is not usually named.

The following problem illustrates the error:

"If you build a fence 100 feet long with posts 10 feet apart, how many posts do you need?"

Many people will immediately answer 10, which is incorrect. The fence certainly has 10 sections, but the posts lie at the boundaries of these section. We can consider each section in turn and place a pole at its left-hand end: thus to for each section there is one pole. However, the common error lies in that the end of the final section has not yet been given a pole: this is the 11th.

Conversely, in a row of 10 lamp-posts there are 9 gaps between them.

In computing, suppose you have a long list or array of items, and want to process items m through n; how many items are there? The obvious answer is n - m, but that is off by one; the right answer is n - m + 1. The "obvious" formula exhibits a fencepost error.

See also zeroth and note that not all off-by-one errors are fencepost errors. The game of Musical Chairs involves a catastrophic off-by-one error where N people try to sit in N - 1 chairs, but this is not a fencepost error. Fencepost errors come from counting things rather than the spaces between them, or vice versa, or by neglecting to consider whether one should count one or both ends of a row.

A rare secondary meaning is an error induced by unexpected regularities in input values, which can (for instance) completely thwart a theoretically efficient binary tree or hash function implementation. The error here involves the difference between expected and worst case behaviours of an algorithm.

An earlier version of this article was based on fencepost error (http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=fencepost_error) at FOLDOC (http://www.foldoc.org), used with permission.

All Wikipedia text is available under the terms of the GNU Free Documentation License

Search Encyclopedia
 Search over one million articles, find something about almost anything!

Featured Article
 Printing press ... where monks wrote them out by hand. Obvously, books were therefore a scarce resource. While it might take someone a year to hand copy a Bible, with the Gutenberg press it ...