I have some question about this code :
#include <iostream>
using namespace std;
int main() {
int i;
int w[10];
cin >> i >> w[i];
cout << i << ' ' << w[i];
return 0;
}
standard inputs are :
3 10
In my PC(Win10 64bit, gcc version : g++ 6.3.0), it occurs segmentation fault.
But other environment(like https://ideone.com/i5Vd7o) can execute it.
It works fine when I edit this section :
cin >> i >> w[i];
to this :
cin >> i;
cin >> w[i];
So 2 small questions come out:
You’re running into undefined behaviour before C++17. When executing
int i;
int w[10];
cin >> i >> w[i];
i
has not been initialised and reading its value is undefined. The line that reads i
and w[i]
attempts to read i
to find out the location of w[i]
before a value is put into i
from the input stream due to C++’s order of evaluation.
Your second statement works, because here i
is read from the standard input, and is subsequently used to compute w[i]
in a separate statement.
In C++17, this behaviour changed, and std::cin >> i >> w[i]
is now well-defined, because the left-hand side of each >>
is computed before the right-hand side, including its computation. This means that in a chain of left-associative >>
invocations, std::cin >> i
is fully executed beforew[i]` is computed.