Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop when using size_t in a count down for loop

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?

  • Using int instead?
  • Using i == 0 as the termination condition? (This would however not work if I need the 0)

I'd appreciate any feedback!

like image 748
AdHominem Avatar asked Dec 10 '16 13:12

AdHominem


2 Answers

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.

like image 163
Yan Zhou Avatar answered Nov 15 '22 05:11

Yan Zhou


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.

like image 24
wildplasser Avatar answered Nov 15 '22 05:11

wildplasser