Why does a loop like this produce an infinite number of 2s?

int main()
{
int y[10];

for (int j=0; j<=10; j++)
{
y[j]=2;
cout << y[j];
}

}

If I remove the '=' it produces the desired amount, but shouldn't it only be one more 2 with the equal sign?
Your code overwrites y[10], which does not exist. It is not part of the array; it is whatever happens to be next to the array. If the value j is being stored there, you'd be overwriting j with 2 and that would make it loop forever.

Don't write into array elements that don't exist. It's very bad.
Last edited on
Topic archived. No new replies allowed.