While writing some code, I came across a problem where values I set were being set wrong. I eventually found the culprit line and while testing around found that it behaved differently on C++14 and C++17. The code is as follows:
#include <stdio.h>
#include <cstdint>
#include <cstring>
int main()
{
uint8_t *p = new uint8_t[3];
memset(p, 0x00, 1);
p++;
memset(p, 0xF0, 1);
p++;
memset(p, 0xFF, 1);
p--;
p--;
// This line in particular
*p++ = *p;
*p++ = 0x0F;
p--;
p--;
printf("Position 0 has value %u\n", *p);
p++;
printf("Position 1 has value %u\n", *p);
p++;
printf("Position 2 has value %u\n", *p);
return 0;
}
On C++14 it prints:
Position 0 has value 240
Position 1 has value 15
Position 2 has value 255
And on C++17 it prints:
Position 0 has value 0
Position 1 has value 15
Position 2 has value 255
I'm curious why it acts differently on different C++ versions. It looks as though on C++14 the *p
right side of the assignment is evaluated after the ++
. Did this change? And if the ++
has precedence, why does it not happen before the dereference on the left side of the assignment operator?