Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

xcode - Integer overflow gives EXC_BAD_INSTRUCTION in Swift

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • Overflow addition (&+)
  • Overflow subtraction (&-)
  • Overflow multiplication (&*)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...