2014-04-27 65 views
2

我遇到以下代碼的問題。 第一個循環打印數組中的所有元素,而第二個for循環不打印任何東西。爲什麼?C++宏 - for循環中的錯誤

#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))      
int array[] = {23,34,12,17,204,99,16};           

int main()                  
{                    
    int d;                  
    //Working                
    for(d=0;d < (TOTAL_ELEMENTS);d++)           
    {                  
     cout << array[d] <<endl;            
    }                  

    //This does not work. Why does this code fail? Isn't it same as the one above? 
    //If I assing TOTAL_ELEMENTS to a variable and then use that in for loop (below), it works! Why?             
    for(d=-1; d < (TOTAL_ELEMENTS);d++)           
    {                  
     cout << array[d + 1] << endl;            
    }                  
}  

任何幫助表示讚賞。

+0

爲什麼你應該總是用-Wall *編譯的另一個原因。 (「警告:有符號和無符號整數表達式之間的比較」)。 (我認爲VC++ equialent是/ Wall)。 – rici

回答

5

sizeof操作者返回一個size_t值,這是一個無符號整型,所以在這個循環:

for(d=-1; d < (TOTAL_ELEMENTS);d++) 

-1被轉換爲一個非常大的無符號整數值。