Nested for-loop without braces

Hi, I wonder what’s the right way to concisely write down a nested-for loop without braces.

Why can I do:

    for (0..3) |i| x += i;

But not:

pub fn main() void {
    var x: usize = 0;
    for (0..3) |i| x += i;
    for (0..3) |i| for (0..3) |j| x += i * j;
}

Error:

nested_for.zig:4:20: error: invalid left-hand side to assignment
    for (0..3) |i| for (0..3) |j| x += i * j;
                   ^~~~~~~~~~~~~~~~

Apparently, the Zig compiler tries to include the inner for-loop in the left-hand side of the assignment. But why doesn’t it cause any problems with a single for-loop.

Is this a bug or intended behavior? And what’s the concise way to write it? Or do I need braces here?

1 Like

I think this is a bug, but the reason for that is that the first for is a statement, the second one is an expression. You don’t have to add ; after for statement with braces, that’s why it is treated explicitly as a statement by the grammar.

This reminds me a bit of:

Yeah too bad this is not possible. I like these little one-liners.