7

While messing around with Swift, I noticed that when the 64 bit integer overflows, I get the following error:

file:///Users/user/Documents/playground/MyPlayground.playground/: error: Playground execution aborted: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

func fibonacci(which: Int) -> (fibOf: Int, isEqualTo: Int) {
    var i = 1, j = 1

    for var k = 2; k < which; k += 1 {
        let tmp = i + j // this line is highlighted when error occurs
        j = i
        i = tmp
    }

    return (which, i)
}

print (fibonacci(92))
print (fibonacci(93)) // this triggers an error

The first call, i.e. with 92 as argument, will run fine. When supplying the 93 value however, I get the irrelevant EXC_BAD_INSTRUCTION error. Is this a bug or what? Normally I'd expect it to overflow.

Siyual
  • 16,415
  • 8
  • 44
  • 58
BitParser
  • 3,748
  • 26
  • 42
  • I found this by googling "Swift integer overflow": https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html#//apple_ref/doc/uid/TP40014097-CH27-ID37 – Aaron Brager Jul 14 '15 at 21:24

1 Answers1

12

It is expected behaviour. If you want to overflow, you need to use overflow operators.

  • Overflow addition (&+)
  • Overflow subtraction (&-)
  • Overflow multiplication (&*)
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
Tomáš Linhart
  • 13,509
  • 5
  • 51
  • 54