Operator precedence

220 views
Skip to first unread message

Scott Pakin

unread,
May 29, 2021, 6:54:13 PM5/29/21
to golang-nuts
When the Operator precedence section of the language specification says that "Binary operators of the same precedence associate from left to right. For instance, x / y * z is the same as (x / y) * z", does this imply that the language guarantees that a*3.0/2.0 will always be evaluated as (a*3.0)/2.0 and never as a*(3.0/2.0), even though the constant expression can be computed at compile time?  Does this hold for integer types, too (e.g., a*3/2)?

Thanks,
— Scott

Axel Wagner

unread,
May 29, 2021, 7:03:57 PM5/29/21
to golang-nuts
I would read it that way, yes. Note that regardless of the spec you can always indicate the intended precedence using parenthesis. If in doubt, I'd recommend to do that - if you are in doubt, the reader of the code will be as well.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/4f64105d-7ecb-4cf8-a18f-d045ace5e9ecn%40googlegroups.com.

Keith Randall

unread,
May 29, 2021, 9:44:39 PM5/29/21
to golang-nuts
Yes, Go will evaluate as specified in the spec. So it can't do (a*3.0)/2.0 as a*(3.0/2.0). At least, it always needs to produce results *as if* the former was used.
Normally for floats that means it does the ops exactly in the order specified. For integers there are often rewrites that will make it faster but still produce the results required by the spec. e.g. (2*x)+(2*y) == 2*(x+y) works for ints (but not floats).

Message has been deleted

Scott Pakin

unread,
Jun 6, 2021, 4:44:44 PM6/6/21
to golang-nuts
Axel and Keith: Thanks for responding.  I'm glad it sounds like I'm reading the spec correctly—and that Go shouldn't do anything sneaky with evaluation order.
Reply all
Reply to author
Forward
0 new messages