Const statements, if they do the same thing as #ifdef macros in Go?

No text preprocessing in Go. Like Java and others like that, if I want to remove a block of code, I can use the value of const and surround the code with if .

If I do this, does the compiler optimize the code from the AST and outside the generated code? Or is this condition fulfilled every time?

EDIT: If I want to replicate #ifdef , what is the best way to do this?

+4
source share
1 answer

If statements with constant conditions do not match with #ifdef , because the code inside is always compiled no matter what. However, compilers optimize it whenever possible. Consider this program:

 package main import ( "fmt" ) func main() { if false { fmt.Println("Hello, world!") } } 

If we run go tool 6g -S test.go , the assembly for the main function is displayed here:

 --- prog list "main" --- 0000 (test.go:7) TEXT main+0(SB),$40-0 0001 (test.go:11) RET , 

The dead code has disappeared, so all it does is return.

If you really need to conditionally compile parts of your code, it is best to do this through the build system.

+8
source

All Articles