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
?
Unreachable code is an atom or sequence of atoms which cannot be executed because there is no way for the flow of control to reach that sequence of atoms. For example, in the following atom sequence the MUL, SUB, and ADD atoms will never be executed because of the unconditional jump preceding them.
Unreachable code error occurs when the code can't be compiled due to a variety of reasons, some of which include: infinite loop, return statement before the unreachable line of code.
GNATprove detects and issues warnings about both the dead code and the unreachable code.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With