Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined behavior, or: Does Swift have sequence points?

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

  • Why are these constructs (using ++) undefined behavior?
  • Undefined behavior and sequence points

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?

like image 788
Martin R Avatar asked Sep 21 '15 22:09

Martin R


1 Answers

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.

like image 94
Martin R Avatar answered Oct 07 '22 10:10

Martin R