Infinite loop when using size_t in a count down for loop

后端 未结 7 1229
走了就别回头了
走了就别回头了 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:05

    It is not technically an overflow because size_t is an unsigned type, but it is definitely an infinite loop since the termination condition is always true.

    Unsigned integers wrap around when decremented at 0. Note that your loop will run 11 times before the wrap around occurs, not 10.

    You must check for the condition before decrementing the index. Starting the enumeration with an initial value one more than the maximum valid index improves visual consistency and simplifies the test.

    Here is a corrected version where you can see that the initial value for i is the number of elements of the array:

    int array[11];
    for (size_t i = 11; i-- > 0; ) {
        // Do something, f.ex. array[i] = i
    }
    

提交回复
热议问题