1

I want make some simple loop like this:

package main

import "fmt"

func main() {
    var i uint32 // code bellow works fine with int32
    for i = 31; i >= 0; i-- {
        fmt.Println(i)
    }
}

But this loop is endless, if i has type uint32. If i is int32 it`s ok.

How I can break this loop, if i has type uint32 without checking if i == 0?

3
  • 1
    Well... i can't be negative so you have to check when it goes to 0. Commented Jun 13, 2018 at 7:58
  • 1
    Or you use an int32. Commented Jun 13, 2018 at 7:59
  • All values of an unsigned integer is positive...therefore your condition will always be true. Commented Mar 8, 2019 at 17:29

1 Answer 1

4

i is of type uint32, so once it reaches 0, decrementing again will result in the max value of uint32. Change the loop condition to check for that:

var i uint32 // code bellow works fine with int32
for i = 31; i != 0xffffffff; i-- {
    fmt.Println(i)
}

Try it on the Go Playground.

Or use the math.MaxUint32 constant:

var i uint32 // code bellow works fine with int32
for i = 31; i != max.MaxUint32; i-- {
    fmt.Println(i)
}

Or use the ^uint32(0) expression, where the ^ operator is the bitwise complement operator, applied on 0 will give you a value where all the bits are ones: the max value for uint32.

Although if you look at the code, it's not intuitive, hard to understand. So you should use alternatives where this is not required and are more straightforward, such as using int32 and checking for i >= 0, or use an upward loop, such as:

for i := uint32(0); i < 32; i++ {
    fmt.Println(31 - i)
}

Or offset the loop variable's range with +1, so you can test for i >= 1 or i > 0:

for i := uint32(32); i > 0; i-- {
    fmt.Println(i-1)
}
Sign up to request clarification or add additional context in comments.

4 Comments

You forgot the disclaimer: "don't do that to keep the code readable".
Thanks for the constant max.MaxUint32. I was looking for her :) Solved.
i != ^uint32(0) would also do without resorting to importing math.
@kostix True, I forgot about that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.