6

Is (++i)++ undefined behavior? Is it possible that the side effect of prefix increment happens after retrieving the incremented object for postfix increment to operate on? That would seem strange to me.

My gut feeling says this is undefined in C++03 and well-defined in C++11. Am I right?

sbi
  • 219,715
  • 46
  • 258
  • 445
fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • 43
    Why the eff do so many people ask questions about this? Just don't do it. Who cares what it does - **It's terrible code, and should never be written anyway.** – jjnguy Dec 03 '10 at 15:31
  • 13
    @jjnguy: I would draw a distinction between "should never be written" and "should never be used in production code that does anything important." It's often good to write known bad code in order to learn from it. Fail things in a controlled way, test the predicted failures, etc. – David Dec 03 '10 at 15:33
  • 16
    there should be a dedicated stackoverflow site for undefined behavior questions in C++ – Idan K Dec 03 '10 at 15:35
  • 1
    I understand the value of basic research. But I, for one, have had my fill of these questions especially given that you wrote the FAQ on the topic. Enough with the obsession over UB, already. – John Dibling Dec 03 '10 at 15:37
  • @Idan K: See also: [what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-abo](http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-abo) – Martin York Dec 03 '10 at 15:41
  • 1
    The proposed duplicate is about common undefined behavior, and dates from 2008. This question is about C++03 (which is covered by the duplicate) and C++0x (which isn't). – David Thornley Dec 07 '10 at 17:18
  • possible duplicate of [Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc...)](http://stackoverflow.com/questions/949433/could-anyone-explain-these-undefined-behaviors-i-i-i-i-i-etc) – Bo Persson Mar 06 '12 at 18:06

2 Answers2

11

My gut feeling says this is undefined in C++03 and well-defined in C++0x.

Yes you are right. The behaviour is undefined in C++03 because you are trying to modify i more than once between two sequence points.

The behaviour is well defined in C++0x because (++i)++ is equivalent to (i += 1)++. The side effects of the += operator are sequenced relative to ++ (post increment) and so the behaviour is well defined.

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
  • Also important is from the definition of postfix-++, "The value computation of the ++ expression is sequenced before the modification of the operand object." So we know the `++i` must have completed before the side-effect of the postfix-++ – M.M Jul 11 '20 at 09:27
-1

This is an undefined behaviour since i is being modified more than once between two sequence points.

Sunil
  • 856
  • 12
  • 24