0

As I may know that shift operator << doesn't guarantee the order of evaluation of it its operands so an expression like this:

int i = 0;
cout << i << i++ << endl; // UB

But I think the new standard C++17 adds the shift operator to sequenced operators which guarantees to evaluates its lhs operand then its rhs.

So the expression above if compiled using C++17 or C++20 it will be ok:

int i = 0;
cout << i << i++ << endl; // 00
  • But when I compile it using GCC and CLang passing -std=c++17 and -std=c++2a I get the same warning operation on 'i' maybe undefined [-Wsequence-point].

So Is it safe to do so or it is UB that I should never do? Thank you.

Maestro
  • 2,512
  • 9
  • 24
  • You shouldn't do it even if it is well-defined, because it's not *immediately* obvious to the reader what is going on/what you *intended* to do. Avoid pre/postfix increments in the middle of other expressions. – Nicol Bolas May 06 '20 at 15:53
  • @NicolBolas: I don;t think so because in the standard it is well-defined and sequenced: https://stackoverflow.com/questions/51784836/shift-operands-sequenced-in-c17 This is from the link above to my question. – Maestro May 06 '20 at 15:58
  • Code is read more often than it is written; if you have to ask "what is this code doing, and did the programmer mean to do that?" then you've failed at writing readable code. It is unreasonable to expect a programmer to know enough about the language to know exactly what this code will do simply by inspection. – Nicol Bolas May 06 '20 at 16:00
  • @NicolBolas: Why it is well-defined by the new standard then? – Maestro May 06 '20 at 16:01
  • Having certain operators mandate sequencing is mainly intended to make fold expressions based on those operators be reliable. Also, there are cases where a value is being invisibly modified (such as `this->func1() << this->func2()`). It's not obviously apparent that these member functions modify the same member variable. But if you are *visibly* modifying the same thing in an expression... just don't. – Nicol Bolas May 06 '20 at 16:06

0 Answers0