Infinite loop when using size_t in a count down for loop

后端 未结 7 1211
走了就别回头了
走了就别回头了 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条回答
  •  Happy的楠姐
    2021-01-13 08:02

    A simplest way is to increase the upper value. For example

    const size_t N = 10;
    
    for (size_t i = N + 1; i != 0; --i) {
        // Do something, f.ex. array[i-1] = i-1
    }
    

    or

    const size_t N = 10;
    
    for (size_t i = N + 1; i-- != 0; ) {
        // Do something, f.ex. array[i] = i
    }
    

    In general case when i can be equal to the maximum value stored in an object of the type size_t you can use the following trick

    #include 
    
    int main( void )
    {
        const size_t N = 10;
    
        for (size_t i = N, j = N; !( i == 0 && j == -1 ); j--)
        {
            i = j;
            printf( "%zu ", i );
        }
    
        printf( "\n" );
    }
    

    Otherwise you can use do-while loop. It is more suitable in this case. For example

    size_t i = N;
    
    do
    {
        printf( "%zu ", i );
    } while ( i-- != 0 );
    

提交回复
热议问题