M
M
Maxim Ivanov2016-09-08 11:03:21
C++ / C#
Maxim Ivanov, 2016-09-08 11:03:21

Why are the elements displayed in a different order in the cout stream?

#include <iostream>
using namespace std;

int main(){

  int* c = new int[3];
  c[0] = 0;
  c[1] = 1;
  c[2] = 2;

         // ждал 0 1 2
 	cout << *c << ' ' << *c++ << ' ' << *c++ <<  endl; // выводит 2 1 0

  return 0;
}

Moreover, if you output in a loop, everything is fine
#include <iostream>
using namespace std;

int main(){

  int* c = new int[3];
  c[0] = 0;
  c[1] = 1;
  c[2] = 2;

  for (int i =0; i < 3; ++i){
    // *c == c[0]
    cout << *c << ' ';

    // *c++ == c[1] 
    // сместили внутренний указатель на одну позицию
    *(c++);
  }

  cout << endl;

  //cout << *c << ' ' << *c++ << ' ' << *c++ <<  endl; // 2 1 0

  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-09-08
@splincodewd

The fact is that between the sequence points (this is a semicolon, a function call and the economical operations &&, || and ?:), the compiler has the right to rearrange the operations as it wants. So he decided to calculate c++ from the end.
In C++11, there are no sequence points, there is “evaluated before”, but this does not fundamentally change the language.
C++17 promises to fix this.
19) In a shift operator expression E1<<E2and E1>>E2, every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2
en.cppreference.com/w/cpp/language/eval_order
PS. MinGW even warns that the result of such a line is not explicitly defined. And on class Co too (see flame with Fat Lorry).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question