On Wed, Jun 19, 2024 at 9:59 AM Oliver Eikemeier
<[email protected]> wrote:
>
> I'm observing some strange behavior and could use some help understanding it.
>
> The specification says: “Pointers to distinct zero-size variables may or may
> not be equal.”
>
> With the following program (Go Playground):
>
> 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?
The specs says, as you say above, "Pointers to distinct zero-size
variables may or may not be equal.” That means that you can't predict
the result of any given comparison of addresses of zero-sized
variables. Could be true, could be false, could change each time you
do the comparison. So this behavior is permitted by the spec.
> Let's try to confuse the optimizer a little (Go Playground):
>
> 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):
>
> 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.
Yes, as the spec permits.
Ian
--
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 [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/CAOyqgcXRr24VJNsbv_-b4HS6XGVBgKcTv5Ny4rsMvHFuMPvkvQ%40mail.gmail.com.