This cycle will end with x
equal to -1
(assuming x
is signed), but its body will not produce access to array[-1]
at the last step. The last array access is to array[0]
. The behavior is consistent across all implementations.
In other words, there's no problem with negative index array access in the code you quoted. But if you attempt to access array[x]
immediately after the cycle, then you'll indeed access array[-1]
.
The code you quoted is a variation of a fairly well-known implementational pattern used when one needs to iterate backwards over an array using an unsigned variable as an index. For example
unsigned x;
int a[5];
for (x = 5; x-- > 0; )
a[x] = 0;
Sometimes less-experienced programmers have trouble using unsigned indices when iterating backwards over an array. (Since unsigned variables never have negative values, a naive implementation of the cycle termination condition as x >= 0
does not work.) This approach - i.e. post-increment in the cycle termination condition - is what works in such cases. (Of course, it works with signed indices as well).