see: https://github.com/golang/go/issues/65878
package main var a, b [0]int var p, q = &a, &b func main() { if (p == q) { p, q = &a, &b println(p == q) // false } } On Thursday, June 20, 2024 at 12:59:43 AM UTC+8 Oliver Eikemeier wrote: > I'm observing some strange behavior and could use some help understanding > it. > > The specification <https://go.dev/ref/spec#Comparison_operators%E2%80%9D> > says: *“Pointers to distinct zero-size variables may or may not be > equal.”* > > With the following program (Go Playground > <https://go.dev/play/p/D41jZhecbyK>): > var ( a struct{} b struct{} eq = &a == &b ) func f1() { println("&a:", > &a) println("&b:", &b) println("&a == &b:", eq) } > > > I'll get > &a: 0x537580 &b: 0x537580 &a == &b: false > > > Okay, a and b are empty structs, do not escape, so they share the same > address - fine. Also, some optimizer sees that a and b are different > variables, so their addresses must be different, and decides to make &a > == &b a constant - wrong, but I can live with that. > > My question would be: Is this behavior expected, somehow defined by the > specification, or is it undefined behavior? > > Let's try to confuse the optimizer a little (Go Playground > <https://go.dev/play/p/_r5WEULKPKd>): > var ( a struct{} b struct{} aa = &a ba = &b eq = aa == ba ) func f1() { > println("&a:", aa) println("&b:", ba) println("&a == &b:", eq) } > > results in > &a: 0x5375a0 &b: 0x5375a0 &a == &b: true > > > Mission accomplished, too complicated to calculate in advance. But globals > are bad, so (Go Playground <https://go.dev/play/p/SleVYsVj3u5>): > func f2() { var ( a struct{} b struct{} aa = &a ba = &b eq = aa == ba ) > println("&a:", aa) println("&b:", ba) println("&a == &b:", eq) } > > &a: 0xc000046740 &b: 0xc000046740 &a == &b: false > > > Seems like inlining helps generate false answers. > > The interesting part here is that I can create two pointers (which may or > may not be equal per specification), but depending on how I compare them I > get different results. > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/dc252ba1-60dd-4e4c-add7-1dd8e39f12c3n%40googlegroups.com.