0

I was playing around with pointers and got results I did not expect:

#include <iostream>
#include <vector>

int main() {
    int arr[4] = { 1, 2, 3, 4 };
    int* pArr = arr;
    std::cout << "First number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nSecond number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nThird number: " << *pArr << " at address: " << pArr;
    pArr++;
    std::cout << "\nFourth number: " << *pArr << " at address: " << pArr;
    
    int* pArr2 = arr;
    std::cout << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n"
        << *pArr2++ << "\n";
    /*
    int* pArr2 = arr;
    std::cout << "\n"
        << ++ * pArr2 << "\n"
        <<  * ++pArr2 << "\n";
    */
}

The two different results:

1 2 3 4 - as expected using the first method

4 3 2 1 - using cout with multiple arguments I do not know the proper name.

So my question is - why does this happen? Using multiple cout statements results in expected for me code, while using just 1 cout results in backwards solution.

Results screencap

As a side note, another confusing thing to me is that pre-increment results in all values being equal. In the commented bit of code, the result is 3 3, no matter the ++ placement with respect to the *.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

5

This code:

std::cout << "\n" << *pArr2++ << "\n";
std::cout << "\n" << *pArr2++ << "\n";

has a well defined order of modifications to pArr and will print

1
2

But this code:

std::cout << "\n" << *pArr2++ << "\n" << *pArr2++ << "\n";

invokes undefined behavior before c++17, because there are multiple modifications to pArr2 that are unsequenced. The program has UB, so it could print anything.

From c++17, there is a sequence point between the modifications, and the above code is guaranteed to print:

1
2
cigien
  • 57,834
  • 11
  • 73
  • 112
  • cigien, do me a favour and take a look at this one: https://stackoverflow.com/questions/62666619/chained-ostream-internal-behavior-and-their-results-on-msvc-versus-clang if you have the time. I've been trying to figure out for the past few days if the asker's tripped over a bug in MSVC or if I've missed something. – user4581301 Jul 03 '20 at 16:23