Kagon Khan
Kagon Khan

Reputation: 3

Cout printing with array pointers - weird behavior

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 *.

Upvotes: 0

Views: 277

Answers (1)

cigien
cigien

Reputation: 60430

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

Upvotes: 5

Related Questions