Golang for loop exceeding the condition limit

A simplest code taken from the golang tour website

package main

import "fmt"

func main() {
sum := 1
for sum < 1000 {
	sum += sum
}
fmt.Println(sum)
}

The result is 1024, even when I change the condition to sum < 999, in fact it will output 1024 even till the sum < 600 if I go little below than that, it outputs 512.

I have been working with golang for some time (3 yrs.) and never noticed this, don’t know how I missed such a glaring implementation.

Can someone explain why it is, I expect the program to terminate when it reaches the condition but it is working in the factors of 2^n. Is it some kind of memory optimisation. How to write my program for it to behave correctly and terminate at the condition ?

Just to be clear, I expect the output to be 1000 exactly. So the last cycle of loop should only be executed when it reaches sum == 999. Then finally it should add 1 to it and sum should become 1000.

Never mind I miss understood the code it is not an increment by 1 but by the updated value of sum. Closing the topic.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.