#Reasoning behind block labels

1 messages · Page 1 of 1 (latest)

torpid jasper
#

Why were labels for blocks added in zig? I get that they can be helpful, but the control flow feels much harder to understand. It's similar to goto in C

severe linden
#

the most obvious use case to me is when you need to break out of nested loops. labelling the outside loop and breaking from it by name is a much nicer solution (and you can't cause as many problems as goto).

willow mist
#

The issue with goto in C was less that it was a jump, so I understand, and more that it was an unstructured jump.
It makes it easier to reason about if it's tied to a scope.
Break-to-label is a structured goto.

#
if (cond) goto end;
if (!foo) goto end;
...
end:;
end: {
    if (cond) break :end;
    if (!foo) break :end;
    ...
}
stable frost
#

so you can declare const variable easily without having to create a function:

const readOnly = blk: {
    // Complex operations here
    break :blk [RESULT]
};
stable frost
buoyant jolt
#

Nope, you’d have to (ab)use a loop for that

echo moat
#

being able to goto arbitrary locations in code means a very shakey definition for variable initialisation and the like

buoyant jolt
#

Actually I think you can continue a label?

echo moat
#

no

buoyant jolt
#

Oh, thought I saw that somewhere

echo moat
#

block labels provide forward jumps, loops provide backward jumps

#

technically tail recursion also provides backward jumps in a sense

#

but all in all, the point is that it's all structured

frozen needle
buoyant jolt
#

Ah okay. Makes sense

plucky tartan
echo moat
#

sure, that's how they've defined it