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?
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?
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.
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.
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;
}