It is recommended not to modify an object more than once in a single expression nor using it after modifying it in the same expression.
int i = 0;
++++i; // UB
++i = i++; // OK?
So what do you think? and can you explain to me what value should i
in the last expression be ++i = i++;
?
I know it is of bad design to do so but it is just for education purpose. Thank you.
When I compile against C++17 or C++20: g++ main.cpp -std=c++17 -o prog -Wall -pedantic
I still get the same warning:
++i = i++;
This is the output from GCC:
main.cpp: In function ‘int main()’: main.cpp:12:12: warning: operation on ‘i’ may be undefined [-Wsequence-point] 12 | ++i = i++; | ~^~
.
There's no sequence points now: we have sequenced-before and sequenced-after. When you have an operator=
call (or any other operator@=
call - built-in operator=
or user-defined call), right-hand side is sequenced-before left-hand side. So ++i = i++
is valid in C++17, with i++
sequenced-before ++i
.
Before C++17, as you wrote, it was UB.