You can fix the end condition from your original code. -1/2
is guaranteed to be 0 in C99, which makes the loop body execute once, so you might have to treat count == 1
specially if that's still the required behavior once the types are unsigned.
size_t count = something;
if (count > 1) {
for (size_t start = (count-2)/2; start != SIZE_MAX; --start) {
someFunction(x, start, count);
}
}
This works because we know that the initial value of start
cannot possibly be SIZE_MAX
, because there is no value of size_t
that when divided by 2 yields SIZE_MAX
.
For more general loops, that might need to start at SIZE_MAX
and go all the way down to 0 inclusive, clearly we cannot perform the exit check before the loop body, because we want the loop body to execute once for every value of size_t
, so there is no value on which we can exit. To allow for that case:
size_t count = SIZE_MAX, start = SIZE_MAX;
do {
someFunction(x, start, count);
} while (start-- != 0);
In all cases, SIZE_MAX
can be replaced with -1
, which is more generic in that it converts to the max value of every unsigned type, but leads to confused questions.