Reputation: 1283
I don't understand what is happening here. There must be something related to "flush" termen but I would like an explanation.
int arr[4] {3,8,1,6};
cout<<arr[0];
cout<<arr[1];
cout<<arr[2];
cout<<arr[3];
cout<<endl;
cout<<&arr[0]<<endl;
cout<<&arr[1]<<'\n';
cout<<&arr[2]<<endl;
cout<<&arr[3]<<endl;
cout<<&arr[0]<<endl;
int *j = &arr[0];
cout << *j << *(++j) << *(++j) << *(++j); // HERE IS THE PROBLEM
Why this last cout
instruction tends to output the numbers reversed?
It seems to me like backtracking but I'm not sure.
I was expecting 3816
as output, instead I got 6618
.
Upvotes: 1
Views: 102
Reputation: 23832
In the expression
cout << *j << *(++j) << *(++j) << *(++j);
The order of evaluation is not well defined, so the behaviour is undefined.
Examples of undefined behavior are memory accesses outside of array bounds, signed integer overflow, null pointer dereference, more than one modifications of the same scalar in an expression without any intermediate sequence point (until C++11) that are unsequenced (since C++11)
I ran it and it outputed 3816
. Note that with warning flags this is detected by the compiler.
If you try:
cout << *j;
cout << *(++j);
cout << *(++j);
cout << *(++j);
This well sequenced expression will render the expected output.
Upvotes: 5