`while` loops: why count in the continue expression and leave the body empty?

While looking through std I found several places where something is being counted with a while, but the counting is done in the continue expression, and the body is left empty. Basically like this:

while (predicate) : (counter += 1) {}

Why does someone do this? What’s the benefit compared to the simpler

while (predicate) counter += 1;

?

1 Like

The two examples you provide are functionally identical. The first example (with the continuation expression) is “idiomatic” Zig, while the second just works.

However, when the body of the loop is not empty, incrementing counter can be seen as additional noise that doesn’t contribute to the work the loop is doing. This is the benefit (IMO) of doing it this way: the body of the while loop contains the “work,” and the continuation expression defines what happens after a loop iteration.

The reader of the code need not search through the body of the while loop to determine iteration semantics - they’re located in the continuation expression.

As far as its history goes, I’m not too sure, as I could only find one relevant issues (perhaps I could find more if I spent more time searching :face_with_tongue:): add optional second parameter to while loop which is expression to run when loop continues · Issue #139 · ziglang/zig · GitHub

9 Likes

I almost never use the continue expression. I think it just spreads logic around. It’s one more thing to keep in your head when thinking through control flow.
Also, my most common while loop is, by far while(true).