Main Page | See live article | Alphabetical index

Off by one error

An off by one error in computer programming is an avoidable error in which a loop iterates one too many or one too few times than desired. Usually this problem arises when a programmer fails to take into account that a sequence starts at zero rather than one, or makes mistakes such as using "is less than" where "is less than or equal to" should have been used in a comparison.

For example, in the C programming language, a loop that iterates 5 times would be written as follows:

unsigned i;   // a temporary variable for counting
for( i = 0; i < 5; ++i ) {
    /* do stuff */
}

However, if the comparison used were <= (less than or equal to) or i were initialized to 1 rather than 0, an off by one error would result.

See also Fencepost error.