2

In my cout statement:

cout << ia[cnt++] << "\t" << *beg << "\t" << beg++ << endl;

beg++ affects the output of the earlier *beg statement, and I can't understand why?

Full code:

int ia[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int *beg = begin(ia);   // pointer to the first element in ia
int *last = end(ia);    // pointer one past the last element in ia
int cnt = 0;

while (beg != last)
{
    cout << ia[cnt++] << "\t" << *beg << "\t" << beg++ << endl;
}

Moving the incrementation of beg to after the cout statement causes the code to function as I would expect. Can anyone please explain what's happening here?

sgccarey
  • 492
  • 2
  • 6
  • 16
  • According to the answers on [The result of int c=0; cout< –  Oct 27 '14 at 11:01
  • Besides the unspecified order of evaluations of subexpressions (as explained in the duplicate), you also have undefined behaviour - unsequenced access and modification of `beg`. The code is illegal and practicaly anything can happen. See [this thread](http://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior) for more information. – jrok Oct 27 '14 at 11:15
  • @remyabel this is also true. – n. m. could be an AI Oct 27 '14 at 12:29

0 Answers0