Understand the execution flow of the following program

func main() {

i, j := 10, 10

var sum1, sum2 int

sum1 = (i / 2) + think(&i)

sum2 = think(&j) + (i / 2)

fmt.Printf(“Value of sum1 is %d and sum2 is %d”, sum1, sum2)


func think(k *int) int {

*k += 4

return 3*(*k) - 1

The output from this short program is sum1=sum2=48. How is go evaluating it?

Hi and welcome :slight_smile: ! Go is eager and static but not a truly deterministic programming language. So the result is 48 and 48 because think(&1) is executed before (i/2), or rather: sum1 = (7) + 41. For sum2 is the same. Go doesn’t force the evaluation of the right or left operand in the sum expression. This behavior seems error prone but pushes you a lot to write more clear code, decomposing complex statements and expressions.
For more informations let’s see this.

1 Like