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型:blog
#define TOTAL_ELEMENTS (int)(sizeof(array)/sizeof(array[0]));
int類型默認是有符號的!!!class