c++c++17assignment-operatorsequence-points

Is assignment operator a sequence point under C++17? and what would be the result of this expression?


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.

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++; | ~^~.


Solution

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