0
int a[5] = {1,2,3,4,5};

for (int i = 0; a[i]; i++)
{
    cout << i;

}

This code produces the output of "0 1 2 3 4". What does it compare a[i] against, and how does it know to stop at the end of the array and not go over?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
1110101001
  • 4,662
  • 7
  • 26
  • 48

3 Answers3

3

You code causes undefined behaviour. The expression a[i] will evaluate as true if non-zero and as false if zero. When you run it, you're getting lucky that there is a 0 word immediately following your array in memory, so the loop stops.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
0

It's reading past the array and the memory there just happens to be zero, by sheer luck. Reading past the end of that array is undefined behavior and the outcome might change at any time, so never rely on it.

Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
0

You can think of a[i] as being compared to 0, it simply fetches the number retrieved from the location in memory and if 0 is the value that lives at that memory, then the loop exits, if it is any other number the loop continues.

Suppose an int is 4 bytes on the system. a is given an address, lets pretend it is 0xFF00 when we try to evaluate a[0] we retrieve the data value stored at memory 0xFF00. a[1] would retrieve data from memory 0xFF04, etc. Your program only assigns values to the first 5 memory locations, so when we retrieve the data at beyond these locations they could be anything from 0 to INT_MAX. If it happens to be 0 then the loop exits, however if it happens to be something else the loop continues.

Your could adjust your program like so to see it better:

#include <iostream>
using namespace std;
int main() {
    int a[5] = {1,2,3,4,5};
    int i;
    for (i = 0; a[i]; i++)
    {
        cout << "At memory address: " << &a[i]
             << " lives the value: " << a[i] << endl;
    }
    cout << "At memory address: " << &a[i]
         << " lives the value: " << a[i]
         << ", and this is why the loop ended." << endl;
    return 0;
}
Leonardo
  • 1,452
  • 3
  • 15
  • 26
  • But `a[i]` is compared to 0! – Matti Virkkunen Oct 09 '13 at 01:45
  • @MattiVirkkunen I guess you could put it that way too, but I think usually what often happens is the `TEST` instruction is used here to compare the register with itself. http://stackoverflow.com/questions/6002079/x86-assembler-use-of-test-instruction – Leonardo Oct 09 '13 at 01:51
  • 1
    The operation being performed is still a comparison, regardless of how it's implemented. And the TEST instruction does involve comparing the value with zero inside, how else would it know if it's zero. – Matti Virkkunen Oct 09 '13 at 01:54
  • 1
    @MattiVirkkunen Good question, I guess if we want to remain in the scope of C++ we can just say it compares to 0 for simplicity as you said. – Leonardo Oct 09 '13 at 01:58