整数溢出在 Swift 中给出 EXC_BAD_INSTRUCTION [英] Integer overflow gives EXC_BAD_INSTRUCTION in Swift
问题描述
在使用 Swift 时,我注意到当 64 位整数溢出时,我收到以下错误:
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/:错误:Playground 执行中止:执行被中断,原因:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0).
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
第一次调用,即以 92 作为参数,将运行良好.然而,当提供 93 值时,我得到了不相关的 EXC_BAD_INSTRUCTION 错误.这是错误还是什么?通常我希望它会溢出.
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.
推荐答案
这是预期的行为.如果要溢出,则需要使用溢出运算符.
It is expected behaviour. If you want to overflow, you need to use overflow operators.
- 溢出加法(
&+
) - 溢出减法(
&-
) - 溢出乘法(
&*
)
这篇关于整数溢出在 Swift 中给出 EXC_BAD_INSTRUCTION的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!