Analyze constant expressions and evaluation order
Analyze constant expressions and evaluation order
Untyped numeric constants can represent values beyond machine integer widths until a type is required. Constant arithmetic differs from runtime fixed-width operations. In ordinary expressions, function calls, method calls, receive operations and binary logical operations are evaluated in lexical left-to-right order, but Go does not specify every relative operand evaluation order.
package main
import ( "fmt")
const Huge = 1 << 100const Small = Huge >> 99
func main() { fmt.Println(Small) x := uint8(255) x++ fmt.Println(x)}Huge is an untyped constant; Small fits in int when passed to Println. The variable x instead wraps at its unsigned width. Passing Huge directly to Println would require default type int and fail representability.
Expected output:
20Make side effects explicit
package main
import ( "fmt")
func mark(n int) int { fmt.Println(n); return n }func main() { fmt.Println(mark(1) + mark(2)) n := 1 a := n n++ b := n fmt.Println(a, b)}The calls to mark occur in source order. The separate statements for a and b establish an unambiguous sequence. Do not rely on an unspecified relative order between an ordinary variable read and a call that changes it in the same expression. Short-circuit && and || evaluate the right operand only when needed.
Expected output:
1231 2Try it locally
Define Big = 1<<80 as an untyped constant; shift it right by 76 and print the result. Then increment a uint8 variable initially 255 and print it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced type semantics 05: Analyze constant expressions and evaluation order
Check the lesson objective before moving on.
Why can 1<<100 be a valid untyped constant?
What is the safest way to force an order between a variable read and a modifying call?