Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Off-by-one error
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Looping over arrays=== Consider an [[array data type|array]] of items, and items ''m'' through ''n'' (inclusive) are to be processed. How many items are there? An intuitive answer may be {{nowrap|''n'' β ''m''}}, but that is off by one, exhibiting a [[#Fencepost error|fencepost error]]; the correct answer is {{nowrap|''n'' β ''m'' + 1}}. For this reason, ranges in computing are often represented by [[half-open interval]]s; the range from ''m'' to ''n'' (inclusive) is represented by the range from ''m'' (inclusive) to {{nowrap|''n'' + 1}} (exclusive) to avoid fencepost errors. For example, a [[program loop|loop]] that iterates five times (from 0 to 4 inclusive) can be written as a half-open interval from 0 to 5: <syntaxhighlight lang="c"> for (index = 0; index < 5; index++) { /* Body of the loop */ } </syntaxhighlight> The loop body is executed first of all with {{mono|index}} equal to 0; {{mono|index}} then becomes 1, 2, 3, and finally 4 on successive iterations. At that point, {{mono|index}} becomes 5, so {{mono|index < 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: {{mono|index}} takes the values 0, 1, 2, 3, 4, and 5. Likewise, if {{mono|index}} were initialized to 1 rather than 0, there would only be four iterations: {{mono|index}} 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 (programming language)|Pascal]] has arrays with user-defined indices. This makes it possible to model the array indices after the problem domain.
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)