#Isn't this const variable changing in the for loop? Why does it work? (Ziglings exercise 16)

1 messages · Page 1 of 1 (latest)

flat root
#

In the 16th exercise of ziglings, we are learning about for loops, and this is the correct answer in the exercise:
const std = @import("std");

pub fn main() void {
    // Let's store the bits of binary number 1101 in
    // 'little-endian' order (least significant byte or bit first):
    const bits = [_]u8{ 1, 0, 1, 1 };
    var value: u32 = 0;

    // Now we'll convert the binary bits to a number value by adding
    // the value of the place as a power of two for each bit.
    //
    // See if you can figure out the missing pieces:
    for (bits, 0..) |bit, i| {
        // Note that we convert the usize i to a u32 with
        // @intCast(), a builtin function just like @import().
        // We'll learn about these properly in a later exercise.
        const i_u32: u32 = @intCast(i);
        const place_value = std.math.pow(u32, 2, i_u32);
        value += place_value * bit;
    }

    std.debug.print("The value of bits '1101': {}.\n", .{value});
}```
notice, that we are making a `const i_u32` variable, which we declare as the index of the bits. Right? But it means, every time in the loop the index is iterating `+1` changing the i_u32 every time.
What am I missing?
full python
#

The constant is local to the scope, so every iteration it's redefined with the new value

#

if you'd try to assign a new value to it within the same scope, you'd get a compilation error

celest spindle
#

^ const means that the memory cannot be modified through the variable, but not necessarily that the variable lives in read-only memory. The variable is this case will be on the stack. After being initialized, you won't be able to modify i_u32