Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - Weird thing, input got reversed

Tags:

c++

output

input

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!!!

like image 417
stenlytw Avatar asked Mar 06 '14 08:03

stenlytw


3 Answers

This feels like undefined behaviour and compiler dependent:

cin>>a[i++]>>a[i++]>>a[i++];

(masters, please correct me if I'm wrong)

like image 144
Ferenc Deak Avatar answered Oct 08 '22 15:10

Ferenc Deak


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

like image 26
Bathsheba Avatar answered Oct 08 '22 16:10

Bathsheba


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++;
like image 45
fredoverflow Avatar answered Oct 08 '22 17:10

fredoverflow