0

I'm not sure why the out put is reversed in second case. Its probably straightforward but I don't think I can spend more time thinking about this. Any help/suggestions are appreciated. Note compiler is VS2012

double array[] = {10.0,20.0,30.0,40.0,50,60.0,70,80,90,100.0};
double *it = array;
int size = 10;
while(i<size) 
{               
    std::cout << "First : " <<  *it;
    it++;
    std::cout << "   Second : " << *it << std::endl; 
    it++;
    i++;        
}
//output
//First : 10.0  Second : 20.0
//First : 30.0  Second : 40.0
//...and so on

/*
while(i<size) 
{
std::cout << std::setprecision(15) << "First : " <<  *it++ << "   Second : " << *it++ <<  std::endl;
i++;
}
//Output is reversed in this case
//First : 20.0  Second : 10.0
//First : 40.0  Second : 30.0
//...and so on

*/
crashmstr
  • 28,043
  • 9
  • 61
  • 79
itachi
  • 192
  • 2
  • 10
  • 1
    Your commented out code is *undefined behavior*. – crashmstr Oct 21 '14 at 18:04
  • possible duplicate of [unexpected output in cout and printf](http://stackoverflow.com/questions/10925530/unexpected-output-in-cout-and-printf) – crashmstr Oct 21 '14 at 18:04
  • 1
    @crashmstr: The uncommented parts are also undefined behavior, reading well past the end of the array. – Mooing Duck Oct 21 '14 at 18:15
  • @MooingDuck true, there are other problems, but I was focused on their specific question of the "ordering" and that it is covered in other questions. – crashmstr Oct 21 '14 at 18:17

1 Answers1

1

This happens because the assignments are made in undefined order, most probably that is the reason why it shows the values reversed. Source: http://en.cppreference.com/w/cpp/language/eval_order

Alexey
  • 144
  • 2
  • 12
  • That explains. I instinctively thought it was left to right. Thanks – itachi Oct 21 '14 at 18:00
  • Actually, the order of evaluation in a single `std::cout` is undefined (in other words, the order in which the `++` happens). – crashmstr Oct 21 '14 at 18:05
  • @itachi: each `<<` happens from left to right, but the _parts_ going to `<<` may be evaluated in a random order. Given `3*5 - 7*11 - 13*17`, the `-` are done left to right, but the `*` can be done in any random order you wish because they're not connected – Mooing Duck Oct 21 '14 at 18:16
  • Is there another way to get it in a single line? – itachi Oct 21 '14 at 19:01
  • You could increment the iterator before the count and keep the value of each value in a temp variable, and use those variables in cout. Ex: int a=++it; int b=++it; cout...a...b – Alexey Oct 21 '14 at 19:06
  • 1
    @itachi you could use an index instead of a pointer, thus `cout << array[i] << array[i+1]; i += 2;` – crashmstr Oct 21 '14 at 19:14
  • -1, the code causes *undefined behaviour* which is a whole lot worse than "undefined order". – M.M Oct 21 '14 at 20:39