1

I have the following C++ program:

#include <iostream>
using namespace std;

int main() {
    int array[10] = {1,2,3,4,5,6,7,8,9,10};
    int *p1 = array;
    *p1 = 24;
    *p1 = *(p1++);

    for (int i = 0; i < 10; i++)
        cout << array[i] << " ";

    return 0;
}

The output is:

24 24 3 4 5 6 7 8 9 10

Could someone explain how array[1] becomes 24?

According to me, *p1 = *(p1++) uses the original value of p1 and then increments. So, this statement is equivalent to

*p1 = *p1;
p1++;

So, *p1 (array[0]) is merely reassigned to 24 and then p1 is incremented, meaning that it points to array[1]. So how does array[1] become 24?

Edit: Please reopen this thread. I don't know anything about sequence points and the link posted really didn't answer my question.

Siddhartha
  • 209
  • 1
  • 7
  • The compiler would have told you that had you enabled a reasonable warning level. http://coliru.stacked-crooked.com/a/315369d155145154 – Baum mit Augen Dec 04 '15 at 17:36
  • UB as there are no sequence point. – Jarod42 Dec 04 '15 at 17:37
  • The line '*p1 = *(p1++);' has *undefined* behaviour in c++, since you are asking it to store a value in p1 AND move p1, without specifying which order this should occur in. When a program has undefined behaviour, you cannot rely on it doing anything in particular, and complaining that it didn't do what you expected is futile. Answer: don't move p1 AND write to it in a single statement - do it as two statements. – Alex Brown Dec 04 '15 at 20:09

0 Answers0