I found something weird, I tested this code:
#include <iostream>
using namespace std;
int main() {
int i=0, a[5];
cin>>a[i++]>>a[i++]>>a[i++];
for(int j=0; j<i; j++){
cout<<a[j]<<endl;
}
}
With this input:
1
2
3
And got the input reversed like this:
3
2
1
I thought its output should be the same as this code:
#include <iostream>
using namespace std;
int main() {
int i=0, a[5];
cin>>a[i++]; cin>>a[i++]; cin>>a[i++];
for(int j=0; j<i; j++){
cout<<a[j]<<endl;
}
}
Anybody had experienced this before? Thanks.
-Edit-
Thanks all for the answers!!!
This feels like undefined behaviour and compiler dependent:
cin>>a[i++]>>a[i++]>>a[i++];
(masters, please correct me if I'm wrong)
The behaviour of the statement cin>>a[i++]>>a[i++]>>a[i++];
is actually undefined. This is because there are no sequence points.
You don't know when i
will be incremented and your output is therefore not surprising.
See http://en.wikipedia.org/wiki/Sequence_point
cin>>a[i++]>>a[i++]>>a[i++];
is just syntactic sugar for
cin.operator>>(a[i++]).operator>>(a[i++]).operator>>(a[i++]);
Now, the three calls to operator>>
are definitely executed from left to right, but the three arguments a[i++]
can be evaluated in any order. Let's call the arguments x
, y
and z
:
cin.operator>>(x).operator>>(y).operator>>(z);
You might expect the compiler to substitute x
, y
and z
as follows:
int& x = a[i];
i++;
int& y = a[i];
i++;
int& z = a[i];
i++;
But in fact, the compiler is give much more freedom. In your case, it chose:
int& z = a[i];
i++;
int& y = a[i];
i++;
int& x = a[i];
i++;
And as James Kanze points out, it could also have chosen:
int& x = a[i];
int& y = a[i];
int& z = a[i];
i++;
i++;
i++;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With