8

In C/C++, the second statement in

int i = 0;
int j = i++ + i++ + ++i;

invokes both

  • unspecified behavior, because the order of evaluation of operands is unspecified, and
  • undefined behavior, because the side effects on the same object i are unsequenced relative to each other.

See for example

Now, given that Swift was designed as a safe language, what is the corresponding situation here? Is the result of

var i = 0
let j = i++ + i++ + ++i

well-defined? Can one conclude from the language reference in the Swift book that j == 4?

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    This is a good question to ask, but unfortunately, I have a feeling that the answer is currently "nobody knows"... – jtbandes Sep 21 '15 at 22:16
  • @jtbandes: Thanks (but somebody disagrees :) – You are probably right. I have now cross-posted this in the Apple Developer Forum, perhaps that gives some feedback: https://forums.developer.apple.com/thread/20001. – Martin R Sep 25 '15 at 08:40
  • 1
    Awesome — Chris Lattner responded. I was secretly hoping the answer was "left to right" :) – jtbandes Sep 25 '15 at 15:55

1 Answers1

7

The question was answered by Apple developer and Swift designer Chris Lattner in the Apple Developer Forum https://forums.developer.apple.com/thread/20001#63783:

Yes, the result of that expression will always be 4. Swift evaluates expressions left to right, it isn't undefined or implementation defined behavior like C.

Chris also added:

That said, if you write code like that, someone trying to maintain it will probably not be very happy with you

Agreed! It was meant as an extreme example to demonstrate the problem.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    An update: per the now open-source [Swift Evolution]9https://github.com/apple/swift-evolution/blob/master/proposals/0004-remove-pre-post-inc-decrement.md) process, `--` and `++` are to be removed from future Swift versions. – rickster Dec 10 '15 at 20:32
  • @rickster: You are right, thanks for adding the info here! – But even without these operators, the fact that Swift evaluates expressions left to right remains interesting (in my opinion). – Martin R Dec 10 '15 at 21:10