0

I was tinkering with C++ pointer arithmetic and some weird stuff started happening.

int myint[] = {1,2,3,4};
int * pmyint = myint;

pmyint = &myint[0]; 
cout << *(pmyint) << " " << *(pmyint+1) << " "   << *(pmyint+2) <<  " "<< *(pmyint+3) << endl;
cout << *(pmyint++) << " " << *(pmyint++) << " "   << *(pmyint++) <<  " "<< *(pmyint) << endl;

The output for that peice of code is:

1 2 3 4
3 2 1 4

I'm not sure why the second line isn't matching up with the first...

  • 6
    Undefined Behavior – David G Jun 13 '13 at 18:43
  • 2
    It is *usually* (but not always) not defined what happens if you use multiple ++'s in the same expression. You might want to look up the term *sequence point*. – templatetypedef Jun 13 '13 at 18:44
  • Yes, to UB - read up on sequence points – Scott Jones Jun 13 '13 at 18:44
  • See this post http://stackoverflow.com/questions/3986361/behavior-of-post-increment-in-cout – Yang Jun 13 '13 at 18:45
  • @ScottJones From Wikipedia: "In C++, overloaded operators act like functions, and thus operators that have been overloaded introduce sequence points in the same way as function calls." So shouldn't the second line work? – JAB Jun 13 '13 at 18:49
  • I ran the code in Visual Studio 2012 and my output was different (i.e. got the same for both lines). – MrPickle5 Jun 13 '13 at 18:53
  • Alright , thanks for letting me know it's been answered. I just didn't know what to look up :S –  Jun 13 '13 at 18:55
  • @JAB: It would work if `pmyint` was a class (e.g an iterator). This function is not overloaded, since standard C and C++ knows how to increment a `int *` – Mats Petersson Jun 13 '13 at 19:10
  • @MatsPetersson I was referring to the fact that `<<` is overloaded by the `iostream` library. Or is something like `f(f(f(out, i++), i++), i++)` (where the return type of `f()` is the same as the type of `out`) not allowed either? – JAB Jun 13 '13 at 19:21
  • @JAB: I believe it refers to actually calling the `operator++` and `operator--`. So, yes, I beleive `f(f(f(out, i++), i++), i++)` is also undefined. – Mats Petersson Jun 13 '13 at 19:24

0 Answers0