Why does the compiler turn my conditional loop into an infinite one?