Definition
A half-open interval is a range that includes its lower endpoint and excludes its upper endpoint. It is written : the square bracket marks an endpoint that belongs to the range and the round parenthesis one that does not, so the range holds every with . In programming the endpoints are usually whole numbers, such as array §14.5 indexes or memory addresses, and then holds exactly positions. Mathematics also calls half-open; in programming the term normally means .
Where it fits
Main entry: Interval data structure (§14.11).
The interval data structure entry describes structures that store many intervals and find those that overlap a query; this entry covers the endpoint convention they use. Python’s §12.23 range(a, b) and slice s[a:b] stop before b, and C++ marks a sequence by its first element and the position just past its last.
The convention has three useful properties.
Length is one subtraction. holds 2, 3 and 4, and . The inclusive form needs , and a forgotten is a classic off-by-one error.
Adjacent pieces fit exactly. Splitting at any with gives and , with no gap and no overlap.
Empty needs no special value. holds nothing, because no satisfies , and its length is .
All empty intervals hold nothing, but each still records a position. Searching the sorted array , with positions 0, 1 and 2, for the value 7 can return : no element equals 7, and position 2 is where 7 would be inserted.
In C, with one past the end of a buffer is a valid empty range: a pointer one past the last element of an array may be formed and compared, but not read through. To test that bytes at offset fit in bytes, test and ; the overflow-safe range check §4.17 entry explains why can wrongly pass when the sum wraps around.
Limits and common mistakes
Converting to an inclusive last position breaks on the empty range. With 32-bit unsigned integers, for wraps around to 4,294,967,295, so a loop that runs while never stops on its own and reads far past the array. Loop while instead.
The common overlap test for and , and , assumes both are nonempty: for and it reports an overlap, since and . The exact test is , here , which is false.
Covering all addresses of a 32-bit machine needs the end value , which only a wider integer type holds.
Questions answered
How is an empty interval represented?
An empty interval is represented as : a half-open interval, which includes its lower endpoint and excludes its upper endpoint, with both endpoints equal. It contains no position, because no satisfies , and its length is 0, so length code needs no special case. Any works, and can carry meaning, such as where a missing value would be inserted. Do not represent emptiness by , which should be rejected as invalid, and do not convert to an inclusive last position , which wraps around to the largest unsigned value when .
Related entries: Interval data structure (§14.11), Overflow-safe range check (§4.17), Array (§14.5).