What is an off-by-one error? If I have one, how do I fix it?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
An off-by-one error is for example when you intend to perform a loop n times and write something like:
or:
In the first case the loop will be executed
(n - 1)times and in the second case(n + 1)times, giving the name off-by-one. Other variations are possible but in general the loop is executed one too many or one too few times due to an error in the initial value of the loop variable or in the end condition of the loop.The loop can be written correctly as:
A for loop is just a special case of a while loop. The same kind of error can be made in while loops.