今天看书有一个off-by-one error,感觉很陌生,google了一下,wiki上有一些资料。
Consider an array of items, and items m through n (inclusive) are to be processed. How many items are there? An intuitive answer may be n−m, but that is off by one, exhibiting afencepost error; the correct answer is n−m+1.
For this reason, ranges in computing are often represented by half-open intervals; the range from m to n (inclusive) is represented by the range from m (inclusive) to n+1 (exclusive) to avoid fencepost errors. For example, a loop that iterates five times can be written as a half-open interval from 0 to 5:
for (i = 0; i < 5; i++) {
}
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 carried out 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.
Array-related confusion may also result from differences in programming languages. Numbering from 0 is most common, but some languages start array numbering with 1. Pascal has arrays with user-defined indices. This makes it possible to model the array indices after the problem domain.
一大堆英文,哦……no。
简单说的,off-by-one error就是在说数组越界(我的理解),它包含两种情况。就像例子中的for循环,它定义了一个大小为5的数组,如国我们误将判断条件 i < 5 写成了 i <= 5,那么就会触发一个错误,这就是 off-by-one error。还有一种情况是我们将 i 初始化为 1,同样是一个 off-by-one error。
例子中就说了这两种情况,希望大家能够理解。