One-Line-If doesn't link with One-Line-Else?

I confess, I use and abuse the C syntax to do some weird things. On learning Zig, I’ve noticed that there is a particular thing I can’t do the same.

Such as:

if (condition) break;
else continue;

This doesn’t work in v0.16.0:

error: expected statement, found 'else'
                                    else continue;
                                    ^~~~

But if you change it to:

if (condition) { break; }
else continue;

It works fine. It seems to me like this is almost an unintentional issue with the syntax of Zig. Are one-line-else’s intentionally only allowed to link to if-blocks? I don’t really care if this is specifically disallowed, my one-line else was always just an abuse of the way C parses source but it does seem weird considering one-line-else’s are also allowed in other contexts.

I believe the semicolon after the break is what is ending the statement.

4 Likes

@pasta is correct, remove the semicolon from the first branch.

This is because without the block it becomes an expression, which is terminated by a ;, the else is part of that expression so must be before the ;.

zigs rules with ; around expressions and statements are a little inconsistent, that will likely improve in the future.

4 Likes