int array[] = {1,2,3,4};
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int main()
{
int d = -1;
if(d <= TOTAL_ELEMENTS)
printf("TRUE\n");
else
printf("FALSE\n");
}
sizeof()返回类型为无符号整型unsigned int,因此代码中的TOTAL_ELEMENTS值是unsigned int,在比较signed int和unsigned int时,signed int型变量被转换为unsigned int型变量,而-1转换为unsigned int型的结果是一个非常大的正整数,导致if判断为假,输出FALSE。解决办法是强制转换为int型:
#define TOTAL_ELEMENTS (int)(sizeof(array)/sizeof(array[0]));