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. 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 five times would be written as follows:
for(int i = 0; i < 5; i++ ) { /* Body of the loop */ }
The loop body is executed first of all with i equal to 0; i then becomes 1, 2, 3, and finally 4 on successive iterations. At that point, i becomes 5, so i < 5 is false and the loop ends. However, if the comparison used were <= (less than or equal to), the loop would be repeated six times: i takes the values 0, 1, 2, 3, 4, and 5. Likewise, if i were initialized to 1 rather than 0, there would only be four iterations: i takes the values 1, 2, 3, and 4. Both of these alternatives can cause off-by-one errors.
Another such error can occur if a "do-while" loop is used in place of a "while" loop (or vice versa.) A "do-while" loop is guaranteed to run at least once.
Off-by-one errors are a frequent source of bugs in computer software.