So I'm using size_t
instead of int
in any indexing for loop to prevent negative indices. But when counting down, this leads to an overflow:
for (size_t i = 10; i >= 0; --i) {
// Do something, f.ex. array[i] = i
}
What would be a nice way to prevent this?
int
instead?I'd appreciate any feedback!
for (size_t i = 10; i <= 10; --i) // do something
When overflow do happens, it will round to the largest integer and thus the condition will fail.
for (size_t i = 11; i-- > 0; ) {
// Do something, f.ex. array[i] = i
}
Note: The question starts the loop with value=10(which is strange, but not impossible). I start with 11, but the first time the loop body is enterered, it has already been decremented to 10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With