0

I read a bit about undefined behavior regarding side-effects and sequence points and their replacement in C++11. (Undefined behavior and sequence points)

It raised the following question. Does this code have defined behavior?

int x = 0;
bool result = ++x > ++x;

Does it matter which C++ standard is used?

Gonen I
  • 3,718
  • 18
  • 41
  • 11
    The REAL answer is: write code where you don't need to worry about stuff like this – Hong Ooi Jan 05 '21 at 09:15
  • Think about it this way: does `bool result = operator>(++x, ++x);` have well-defined behaviour? The asnwer is a resounding no. – Michaël Roy Jan 05 '21 at 09:16
  • @MichaëlRoy This notation for operators takes away their sequencing properties, so you can't really use this reasoning. Also this notation doesn't work for built-in operators. – HolyBlackCat Jan 05 '21 at 09:28
  • Looks undefined to me, check https://en.cppreference.com/w/cpp/language/eval_order to be sure. – HolyBlackCat Jan 05 '21 at 09:29
  • @HolyBlackCat Are you saying that there is a difference regarding sequencing between inline and function notation calls of an operator? That would be surprising to me. (There *may* be a difference regarding sequencing of the subexpression within a larger surrounding expression -- e.g. `op(x++) + x++` is sequenced and defined.) – Peter - Reinstate Monica Jan 05 '21 at 09:31
  • [C++17 evaluation order with operator overloading functions](https://stackoverflow.com/questions/46408002/c17-evaluation-order-with-operator-overloading-functions) and [What are the evaluation order guarantees introduced by C++17?](https://stackoverflow.com/questions/38501587/what-are-the-evaluation-order-guarantees-introduced-by-c17) should be useful to you. – NotAProgrammer Jan 05 '21 at 09:33
  • 1
    @Peter-ReinstateMonica Yep, starting with C++17. Pre-C++17 operators lose their sequencing properties merely when overloaded, regardless of used notation. See (16) [here](https://en.cppreference.com/w/cpp/language/eval_order) and [this](https://en.cppreference.com/w/cpp/language/operators) (ctrl+f "lose their special sequencing properties") – HolyBlackCat Jan 05 '21 at 09:37
  • @HolyBlackCat Well, those operators that sequence the evaluation of their arguments in the first place (i.e. && and ||)). Not directly relevant here. – Peter - Reinstate Monica Jan 05 '21 at 10:46

0 Answers0