#Understanding for loop with an index of iteration

1 messages · Page 1 of 1 (latest)

modern jungle
#

Hi,

Official documentation only says " To access the index of iteration, specify a second condition as well as a second capture value.".

My program example:

const std = @import("std");

pub fn main() void {
    var arr = [_]u8{ 0, 0, 0, 0, 0 };
    for (&arr, 2..) |*val, i| {
        val.* = 1; // this is ok
        val[i] = 1; // panic: index out of bounds
    }
}

Expected behavior: loop starts with i == 2, val == arr[2] and ends with i == arr.len - 1.
Actual behavior: loop starts with i == 2, val == arr[0] and ends (if comment out line with val[i]) with i == 2 + arr.len - 1.
Spent a couple hours in a more complex context to figure it out. 😐

My question: what the second condition actually is and how it is related to the loop? Is it documented or explained anywhere?

tropic bluff
#
const std = @import("std");
const print = std.debug.print;

pub fn main() void {
    var arr = [_]u8{ 0, 0, 0, 0, 0 };
    for (arr[2..], 2..arr.len) |*val, i| {
        val.* = 1; 
        arr[i] = 1; 
    }
}
#

No idea what it means

#

but probably means that separated by a comma you add the range + the capture of the index

#

Surprised it works given that the array and the group are differently sized, maybe I am missremembering some error

#

Basically it just refers of adding this values:

for (arr[2..], **2..arr.len**) |\*val, **i**| {
modern jungle
#

Also documentation says Unbounded range is always a compile error. when iterating over consecutive integers. It's even more confusing to get a runtime error.

tropic bluff
#

The two conditions that a for can accept after all:

  • Indexable item
  • Range
tropic bluff
#

because it's alone

#

what is the bound of that range? No idea

#

while

for(arr, 0..) {}

The limit is the arr len

modern jungle
tropic bluff
#

// Iterate over multiple objects.
// All lengths must be equal at the start of the loop, otherwise detectable
// illegal behavior occurs.

Ranges could be seen as an array with [N,N+1, N+2... M]

#

0.. is just a shorthand we already had in slices

#

slice[2..] // Slice from 2 to the rest of the array

#

that is inherited by ranges

#

for(arr, 2..) // arr is of len N, make an array wiht usizes that starts in 2 and ends in len N so it's correct and we don't fuck up

modern jungle
tropic bluff
#

Sorry for the sloppy explanation kinda late here haha

#

Glad you got something out of it