Hello i need some help understanding


#include <iostream>
using namespace std;

int main()
{
int x[5];
int i;
for (i = 0; i < 5; i++){
x[i] = i;
}
cout << x[i] << " ";

return 0;
}
// I am wondering why does this code output 5, if x[5] is not defined as 5 , last x[i] = i i think its 4 because of the for loop...
Last edited on
Hi Vrsa, the issue is your program invokes undefined behavior, so there's no point in trying to make sense of the output itself.

Your array is declared as having a size of 5.
This means it has 5 slots for numbers to be assigned to.
x[0], x[1], x[2], x[3], and x[4] are valid elements to access. Notice that it starts at 0, not 1.

After the for loop, your i variable still exists and is set to the value 5.
The element at x[5] doesn't exist. You should not try to access it.

You can avoid this problem by limiting the i variable to the scope of the for loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
using namespace std;

int main()
{
    int x[5];
    for (int i = 0; i < 5; i++){
        x[i] = i;
    }
    cout << x[i] << " "; // COMPILER ERROR: i is not defined in this scope

    return 0;
}
Last edited on
Topic archived. No new replies allowed.