2014-04-27 46 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被转换为一个非常大的无符号整数值。