why there is no output for this?
#include <stdio.h>
int main() {
int i;
int array[4] = {10, 25, 36, 42};
// int size=sizeof(array) / sizeof(int);
for (i = -1; i < sizeof(array) / sizeof(int); i++) {
printf("%d ", array[i+1]);
}
return 0;
}
Expected output is 10 25 36 42
Within the conditional expression of the for loop
the variable
ihaving the signed typeintis implicitly converted to the unsigned typesize_tdue to the usual arithmetic conversions because the expressionsizeof(array) / sizeof(int)has the unsigned integer typesize_tand the rank of the typesize_t(that is usually an alias for the typeunsigned long) is greater than the rank of the typeint.As a result the expression
( size_t )-1(the variableiis set initially to-1) that is the left operand of the conditioni < sizeof(array) / sizeof(int)becomes a very big unsigned value due to propagating the sign bit.Try for example this call of
printfSo the condition of the if statement evaluates to logical false.
You could write for example
to get the expected result - to execute the for loop.
Though in any case the loop will invoke undefined behavior because when
iwill be equal to( int )( sizeof(array) / sizeof(int) ) - 1the expressionarray[i+1]will try to access memory beyond the defined array.It will be much better and correct to write