This works because the negative value is cast to an unsigned value. Your machine architecture probably uses two's-complement for negative values, so a value of -2 results in:
0xfffffffe (assuming 32-bit)
When you add this to beg
, it wraps around and provided beg
is greater than or equal to 2, has the effect of subtracting 2 from it. Thus, despite the index being extremely large, it has essentially performed a subtraction. If the value of beg
was 1
or 0
, the error would be "past end" instead.