Go是否会优化掉无法到达的if语句?

huangapple go评论96阅读模式
英文:

Does Go optimize out unreachable if-statements?

问题

Go语言非常不幸地缺乏内置的断言功能。我想以以下方式实现它们:

const ASSERT = true

func SomeFunction() {
        if ASSERT && !some_condition_that_should_always_be_true() {
                panic("错误消息或对象。")
        }
}

我的问题是,如果我定义const ASSERT = false,这个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

得分: 7

正如评论中的人们所指出的,这取决于具体的实现。

gc会将其删除。您可以使用-gcflags '-S'编译程序,然后查看二进制文件中是否包含ASSERT部分。

例如,使用-gcflags '-S'编译以下代码,您会发现第8行和第9行的代码被包含在内,但是将Assert更改为false,它们将不会出现在汇编列表中。

package main

const Assert = true

var cond = true

func main() {
    if Assert && !cond {
        panic("failed")
    }
}

编辑:

至于gccgo,在-O1及以上级别会将此代码删除。您可以通过以下方式编译相同的代码来查看:

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

然后执行以下命令:

objdump -S main

以查看带注释的汇编代码。

英文:

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.

huangapple
  • 本文由 发表于 2015年4月15日 23:20:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/29654175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定