I am asking a user to enter five integers. The iteration index i is declared as size_t. However, I have noticed that the behavior of the second loop is abnormal. When I declare the index as int, there are no issues, and the second loop prints all the data correctly. I need to understand what is happening here so that I can avoid this problem in the future. I am using the C compiler in Windows. The mininal working example is
#include <stdio.h>
int main(void)
{
#define N 5
size_t i; // <-- if replace 'size_t' with 'int' no issue
int a[N];
printf("Enter 5 numbers: ");
for (i = 0; i < N; ++i)
scanf("%d", &a[i]);
printf("\nIn reverse order: ");
for (i = N - 1; i >= 0; --i) // <-- problem here
printf(" %d ", a[i]);
return 0;
}
You cannot write a loop with decreasing index value with the i >= 0 comparison when the index variable is unsigned because an unsigned value is always greater or equal to zero. When i is zero, decrementing it gives it the value SIZE_MAX which is positive and huge, causing a[i] to invoke undefined behavior. It may not crash immediately but most certainly will at some point when a[i] will refer to an invalid address.
The correct idiom for a decreasing loop, that works for both signed and unsigned index variables is this:
for (size_t i = N; i-- > 0;)
printf(" %d ", a[i]);
The loop iterates for all values between N - 1 and 0 inclusively and stops when i reaches 0, which is exactly what you want.
Note that this comparison could be written i --> 0 with exactly the same effect (--> is just 2 tokens -- and > glued in an unusual but meaningful way :) Some people call it the downto operator and it is the subject of one the most active questions on Stack Overflow: What is the '-->' operator in C/C++?
Here is a modified version with a compact idiomatic alternative:
#include <stdio.h>
int main(void)
{
#define N 5
int a[N];
size_t i;
printf("Enter up to 5 numbers: ");
for (size_t i = 0; i < N; ++i) {
if (scanf("%d", &a[i]) != 1)
break;
}
printf("\nIn reverse order: ");
while (i--) {
printf(" %d ", a[i]);
}
printf("\n");
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With