Order of evaluation (does Swift have sequence points?)

(Also posted on stack overflow: http://stackoverflow.com/questions/32705320/undefined-behavior-or-does-swift-have-sequence-points)

In C/C++, the following code exhibits both undefined and unspecified behaviour:


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


The order of evaluation of operands is unspecified, and side effects on the same object

i
are unsequenced relative to each other.


Swift was designed as a safe language, so 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
?

Accepted Reply

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.


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


-Chris

Replies

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.


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


-Chris

Thank you Chris for taking the time to answer, much appreciated. I chose an extreme example to demonstrate the problem. Knowing how Swift evaluates an expression might be useful in real-world cases as well.