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:
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 );