Setting a range for a cyclic transition in the form of a half-closed interval [start, end) , especially for array indices, has some nice properties, as Dijkstra observed in one of his notes .
1) You can calculate the size of the range as a simple end - start function. In particular, if the range is specified in terms of array indices, the number of iterations performed by the loop will be given using end - start . If the range was [start, end] , then the number of iterations would be end - start + 1 - very annoying, right? :)
2) The second observation of Dijsktra refers only to the case of (non-negative) integral indices - with the range indicated as [start, end) and (start, end] both have the property indicated in 1). However, specifying it as (start, end] , you must allow index -1 represent a range of cycles, including index 0 - you allow an "unnatural" value of -1 just for the purpose of representing the range. The agreement [start, end) does not have this problem, because that end is a non-negative integer and, therefore, a natural choice when working with array indices.
Dijsktra evasion of -1 permits a similarity to skipping the last valid container address. However, since the aforementioned convention has been used for so long, it probably convinced the standards committee to make this exception.
source share