Specifying the range to loop over as the half-closed interval [start, end)
, especially for array indices, has certain pleasing properties as Dijkstra observed in one of his notes.
1) You can compute the size of the range as a simple function of end - start
. In particular, if the range is specified in terms of array indices, the number of iterations performed by the loop would be given by end - start
. If the range was [start, end]
, then the number of iterations would have been end - start + 1
- very annoying, isn't it? :)
2) Dijsktra's second observation applies only to the case of (non-negative) integral indices - specifying a range as [start, end)
and (start, end]
both have the property mentioned in 1). However, specifying it as (start, end]
requires you to allow an index of -1
to represent a loop range including the index 0
- you are allowing an "unnatural" value of -1
just for the sake of representing the range. The [start, end)
convention does not have this issue, because end
is a non-negative integer, and hence a natural choice when dealing with array indices.
Dijsktra's objection to allowing -1
does have similarities to allowing one past the last valid address of the container. However, since the above convention has been in use for so long, it likely persuaded the standards committee to make this exception.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…