0

I have detected a difference between VS2019 C++ and VS Code (mingw-w64) about pre post decrement with pointer usage. The following code in VS2019 shows prints the third element of array, 12 (a[2]):

A:

int a[] = { 10, 11, 12, 13, 14 };

int *p = a;
int *q = p + 3;

*q = a[(q--) - p];

cout << *q << endl;

If I change the post decrement operator as pre decrement:

B:

int a[] = { 10, 11, 12, 13, 14 };

int *p = a;
int *q = p + 3;

*q = a[(--q) - p];

cout << *q << endl;

it prints again 12 (a[2])

But if I run the code in VS Code with mingw-w64, then the first code block A: shows the fourth element of the array, 13 (a[3]) and the block B: shows the third element, 12 (a[2])

Why is VS2019 ignoring in this case the pre and post decrement and mingw-w64 not, if I use the same pointer on the left hand side of the assignment, which I use for indexing the array?

Do you have any experience/explanation about this behaviour?

Thank you

Onur

p.s It is an exam question, not a real case. Please don't ask me for a logical use of this code

  • 8
    `*q = ... q-- ...` and `*q = ... --q ...` are both [invoking **Undefined Behavior**](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-pre-and-post-increment-undefined-behavior), see [Order of Evaluation](https://en.cppreference.com/w/cpp/language/eval_order). – Remy Lebeau May 05 '21 at 23:39
  • It is rarely a good idea to too many modifications to a variable on a single line. In this case there are no language guarantees on which will happen first. Usually the implementers of the compiler chose the order that's fastest or easiest to code. – user4581301 May 05 '21 at 23:40
  • 3
    When behaviour is undefined, compilers aren't required to give consistent results. In fact, even if you only use one compiler, the behaviour can vary with settings (e.g. optimisation settings), change when a bug in the compiler is patched, or simply vary with phase of the moon. – Peter May 05 '21 at 23:43
  • The above is why we have a change.org petition to stop the moon from moving. – user4581301 May 05 '21 at 23:57
  • 1
    don't write obfuscated code – rioV8 May 06 '21 at 03:24
  • Does this answer your question? [Undefined behavior and sequence point](https://stackoverflow.com/questions/17574025/undefined-behavior-and-sequence-point) – phuclv May 06 '21 at 04:06
  • Thank you Remy Lebeau and all others commented my question with invoking Undefined Behavior. It is now clear for me – Onur Bassist May 06 '21 at 06:42

0 Answers0