#For loop over consecutive numbers always has a value of type usize

1 messages · Page 1 of 1 (latest)

lusty sorrel
#

I wanted to test the following code

fn GetBit(value: u32, bitNumber: u32) u1 {
    return (value & (1 << bitNumber)) > 0;
}

test "simple test" {
    const minJ: u32 = 1;
    const maxJ: u32 = 5;

    for (minJ..maxJ) |j| {
        GetBit(j, 1);
    }
}
```

This code gives a compile error due to the fact that the j variable is of type usize. I need the types to be this specific because I will update them later to compile type generated integer types that are going to be bigger then 64 bits .

My question are:
- why does this code always return usize as type?
- How would I implement such a loop otherwise?

I hope this is clear enough for everyone to understand as It is my first time working in a systems language?
#

This is the error message I get.

src\main.zig:35:16: error: expected type 'u32', found 'usize'
        GetBit(j, 1);
               ^
src\main.zig:35:16: note: unsigned 32-bit int cannot represent all possible unsigned 64-bit values
src\main.zig:26:18: note: parameter type declared here
fn GetBit(value: u32, bitNumber: u32) u1 {
                 ^~~

faint stratus
#

Working with bits is a bit annoying because of Zig's hard types so I started using std.StaticBitSet; I recommend trying if it applies to your use case.

lusty sorrel
#

@faint stratus I'll have a look thanks.

faint stratus
lusty sorrel
#

Any Idea what the reason is?

faint stratus
#

Not really, I'm also new to Zig; I've even tried |i: u32| but it's not supported.

lusty sorrel
#

same

cursive stump
#

The only way to iterate over other integer types is to use a while loop afaik

var i: i32 = -5;
while (i < 10) : (i += 1) {
    // Loop body
}

Which is equivalent to this for loop in C

int32_t i;
for (i = -5; i < 10; i++) {
    // Loop body
}
faint stratus
lusty sorrel
#

thanks that is then how I'll do it then