Search code examples
zig

What is the syntax for a for loop over an index with increment?


What is the syntax for having a for loop in zig with an increment? In the code snippet below I wrote how it would look like in F#. But how does it look like in zig?

In C it would be something like for (x = 3*x0; x <= x1; x += 2*x0).

fn foo(x0: i32, x1: i32) {
  for (3*x0..2*x0..x1) |x| {
     // ...
  }
}

Solution

  • I'm not a zig expert, but perusing documentation online, it doesn't appear that the zig for loop construct allows for arbitrary iteration. It's less like a C for loop and more like a C# foreach loop.

    You'd want to use a while loop with a continue expression (after the :) in this situation.

    var x : i32 = 3 * x0;
    
    while (x <= x1) : (x += 2 * x0) {
        // body of the loop
    }