Loops and Blocks and Labels

Just a funny I noticed:

What do you think the output of this program would be:

const std = @import("std");
pub fn main() !void {
	var i: u32 = 0;
	while (i < 6) : (i += 1) b: {
		std.debug.print("BLOCK\n", .{});
		if (i >= 3) break :b;

		std.debug.print("LOOP\n", .{});
	} else {
		std.debug.print("ELSE\n", .{});
	}
}

In other words, does breaking out of the then block break out of the loop?

(obviously you can just run the program I am just curious about everyone’s intuition)

4 Likes

Isn’t the break :b; effectively functioning as a continue?

I would expect 6x BLOCK, the first 3 of which followed by LOOP (until the break/continue takes effect) and then the ELSE

4 Likes

It’s the same as if it said continue, right? Don’t show this to andrew, he might remove the keyword for redundancy then :rofl:

15 Likes

Lets quickly flag the post as inappropriate

4 Likes

I think it makes sense to remove continue, even though this keyword has been used to implement state machines in switch statements.

Oh no not another cursed language feature… I love it.

:slight_smile: as long as we can rename break to goto…

1 Like

This is exactly how I “continue” from inline for loops.

Example

3 Likes

The semantics are vastly different: goto refers to jumping to a label, whereas Zig’s break refers to leaving the code block where the label is located.

Obviously the solution is to change the block’s label location to the end of the block.

{
    do();
    if (cond) goto :label;
    domore();
} :label
1 Like

omg… i can’t read this. while...else...

OR, hear me out, make this work:

var i: u32 = 0;
block: {
	std.debug.print("{d}\n", .{i});
	if (i < 10)
		continue :block;
}

so that the continue makes it go back to the beginning of the block.

And remove for and while in its favour :upside_down_face:

/j

3 Likes