简体   繁体   中英

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?
  • I think that the last expression was UB before C++17 standard but now I guess it is OK because the assignment operator has become a sequence point.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM