dseve40868 2015-04-15 15:20
浏览 87
已采纳

Go是否会优化无法访问的if语句?

Go has a very unfortunate lack of built-in assertions. I want to implement them this way:

const ASSERT = true

func SomeFunction() {
        if ASSERT && !some_condition_that_should_always_be_true() {
                panic("Error message or object.")
        }
}

My question is will the if-statement be optimized out if I define const ASSERT = false?

  • 写回答

1条回答 默认 最新

  • dongsha1544 2015-04-15 15:30
    关注

    As noted by the people in the comments to your question, it's implementation-specific.

    gc does remove it. You can build your program with -gcflags '-S' and see that the ASSERT part is not in the binary.

    E.g. compile the following code with -gcflags '-S', and you'll see that the code on lines 8 and 9 is included, but change Assert to be false, and they won't be there in the asm listing.

    package main
    
    const Assert = true
    
    var cond = true
    
    func main() {
        if Assert && !cond {
            panic("failed")
        }
    }
    

    EDIT:

    As for gccgo, it removes this code at -O1 and above. You can see it by compiling the same code with

    go build -compiler gccgo -gccgoflags '-O1' main.go
    

    and then doing

    objdump -S main
    

    to see the annotated assembly.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题