what is wrong with this code ? can anyone explain ?
#include <stdio.h>
#include <malloc.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int num;
int d;
int size = TOTAL_ELEMENTS -2;
printf("%d\n",(TOTAL_ELEMENTS-2));
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
when i print it gives 5, but inside for loop what is happening ?
The
sizeofoperator returns a value of typesize_t, which is an unsigned value. In yourforloop condition test:you are comparing a signed value (
d) with an unsigned value (TOTAL_ELEMENTS-2). This is usually a warning condition, and you should turn up the warning level on your compiler so you’ll properly get a warning message.The compiler can only generate code for either a signed or an unsigned comparison, and in this case the comparison is unsigned. The integer value in
dis converted to an unsigned value, which on a 2’s complement architecture ends up being0xFFFFFFFFor similar. This is not less than yourTOTAL_ELEMENTS-2value, so the comparison is false.