Off-by-one_error Off-by-one_error

Off-by-one error - Definition and Overview

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 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 are off-by-one errors.

Another such error can occur if the difference between a "do-while" and a "while" loop in C programming is not familiarized. The former is guaranteed to run at least once.

Off-by-one errors are a frequent source of bugs in computer software.

See also Fencepost error.

Example Usage of Off-by-one

Kingrashee713: RT @SEXYNIA RT @Kingrashee713: #Quickquestion? @SEXYNIA are u a 36dd?.....34dd <- Damn! off by one! SHITTT! but (.)(.) <-ohh wee! lol
modernjew: Back in May I wrote an article about which new show would be canceled first. Today, Hank got axed. I was off by one: http://tr.im/ELbj
dancameron: @randyalderson yeah, especially when there's no logged errors & it looks like it's working but you find out the config is off by one param.
Copyright 2009 WordIQ.com - Privacy Policy  :: Terms of Use  :: Contact Us  :: About Us
This article is licensed under the GNU Free Documentation License. It uses material from the this Wikipedia article.