2

I have a problem with the following code. The first for loop prints all the elments in the array, while the second for loop does not print any thing. Why?

#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;                                              
    }                                                                       
}      

Any help is appreciated.

AJK
  • 55
  • 5
  • Yet another reason why you should *always compile with -Wall*. ("warning: comparison between signed and unsigned integer expressions"). (I think the VC++ equialent is /Wall). – rici Apr 27 '14 at 02:35

1 Answers1

5

sizeof operator returns a size_t value, which is an unsigned integral type, so in this loop:

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

-1 is converted to a very big unsigned integral value.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294