Infinite loop when using size_t in a count down for loop

后端 未结 7 1147
走了就别回头了
走了就别回头了 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条回答
  •  -上瘾入骨i
    2021-01-13 08:27

    The problem is that in in your implementation size_t has type unsigned long or unsigned int.

    When i=0 the condition is accomplished and --i will transform it to 4294967295UL = ULONG_MAX, so the test condition i >= 0 from the loop will never be false .

    size_t has some unsigned type, i will never be negative.

提交回复
热议问题