Infinite loop when using size_t in a count down for loop

后端 未结 7 1212
走了就别回头了
走了就别回头了 2021-01-13 07:53

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:

<
7条回答
  •  甜味超标
    2021-01-13 08:13

    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.

提交回复
热议问题