英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论