I got into the habit of declaring for
loop indices with size_t
instead of int
. That however already bit me multiple times when I was iterating an array backwards, i.e. checking for the index to be greater or equal to zero:
for (size_t i = n-1; i >= 0; i--) {
// ...
}
When the body has been run for i == 0
, it gets decremented and wraps around, to SIZE_T_MAX
probably. That makes the break condition a tautology. There might be some clever bit manipulations to check for possible underflows, but wouldn't it be simpler to use ptrdiff_t
instead?
What is the proper idiomatic C way to solve this? size_t
plus bit twiddling or ptrdiff_t
and feeling uncomfortable about semantics?