djeetee
djeetee

Reputation: 1837

swift EXC_BAD_INSTRUCTION error in playground

I have the following test code...

import Foundation

var n = 5

let binSlots = 64
var numOfOnes = 0
var inSequence = false

func toThePower(number: Int, power: Int) -> Int {
    var ans = number
    for _ in 1..<power  {
        ans = ans * number
    }
    return ans
}

// the following line is fine
if n <= toThePower(number: 2, power: 4) {
    print("ok")
}

for i in stride(from: binSlots, through: 0, by: -1) {
    // the following line produces this error:
    // // error: Execution was interrupted, reason: 
    // EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
    let pCalc = toThePower(number: 2, power: i) 

    if n >= pCalc {
        n = n - pCalc
        numOfOnes += 1
        inSequence = true
    }
    else {
        if inSequence {
            break
        }
    }
}

Any clues as to what's causing the error? I know that if I comment out the following...

//    for _ in 1..<power  {
//        ans = ans * number
//    }

the error goes away however I don't know why or why the first call to the function runs with no errors.

I have looked at other similar posts but none was similar to my case.

your help is appreciated.

thank you.

Upvotes: 0

Views: 66

Answers (1)

rmaddy
rmaddy

Reputation: 318774

Your error is from this line in your toThePower function:

for _ in 1..<power  {

The problem is that the right side of the range can't be smaller than the left side of the range.

The line:

for i in stride(from: binSlots, through: 0, by: -1) {

results in you calling your toThePower function with a power down to and including 0.

0 is less than 1, hence the crash.

Change:

for i in stride(from: binSlots, through: 0, by: -1) {

to:

for i in stride(from: binSlots, through: 1, by: -1) {

to avoid the crash.

Upvotes: 1

Related Questions