BlackLamb
BlackLamb

Reputation: 21

Pre-increment and post-increment operators in Swift

 //Post and Pre-Increment Test
   func FindValueOFC() -> String
    {
        var a : Int = 10
        var b : Int = 20
        var c = a++ + a++ + b++ + b++ + ++a + ++b
        return "The value Of variable C is \(c)"
    }

    let whatsTheValueOfC = FindValueOFC()
    println(whatsTheValueOfC)

Why does this program prints out The value Of variable C is 98? Logically it should be 96, as a++ + a++ + b++ + b++ + ++a + ++b can be translated to 10+11+20+21+12+22 = 96

Upvotes: 0

Views: 1651

Answers (1)

vacawama
vacawama

Reputation: 154583

Please don't ever do this in a real program. It leads to undefined behavior when you mix multiple mutators in the same expression. There is nothing in the language that guarantees that the pre-increment operator happens immediately before the value is accessed or that the post-increment operator happens immediately after the variable is accessed.

The compiler could have done the pre-increment of a and b first, added up all of the values, and then applied the post-increments. This would have given the result of

11 + 11 + 21 + 21 + 11 + 21 = 96

The point being that many answers are possible and valid, hence the name undefined behavior. It is possible that you would get different answers with different levels of compiler optimization, which could lead to very puzzling differences between your testing and shipping versions of your app.

Upvotes: 2

Related Questions