Infinite loop when using size_t in a count down for loop

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

    size_t i = 10; i >= 0; is never false as size_t is some unsigned type and all values are greater than or equal to zero.

    ... size_t which is the unsigned integer type of the result of the sizeof operator; ...
    C11 §7.19 2

    A good compiler with warnings enabled would have warned about this.
    Hopefully, that infinite loop would never had occurred as an investigation to the warning would have first rectified the problem.


    Best alternative depends on coding goals

    Good code avoids magic numbers like this naked 10. Better if code derived that. In this simple case, it should have been 11.

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

    OTOH, code may have had break conditions in the loop and needs i in later code to indicate array[] usages

    size_t i = A_SIZE;
    while (i > 0) {
      if (...) break; 
      i--;
      // Do something, f.ex. array[i] = i
      if (...) break; 
    }
    // Do something with i
    

    Code may have a contract requirement to use a 10 in various places.

    // Contract says loop must handle indexes 0 to N, inclusive
    #define N 10
    int array[N + 1];
    
    for (size_t i = N; i + 1 > 0; i--) {
      // Do something, f.ex. array[i] = i
    }
    

    Good optimizing compilers will not perform a +1 on each i + 1 > 0, but create equivalent efficient code.

    Code is a fashion that best conveys the overall meaning of the code.

提交回复
热议问题