C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Discussion: A proposed repeat statement for C++

From: David Brown <david.brown_at_[hidden]>
Date: Tue, 17 Nov 2026 16:32:20 +0100
On 17/11/2026 15:37, Ell wrote:
> On 11/17/26 15:17, David Brown wrote:
>>
>> For loops are good when you are iterating over something fixed. They
>> are not usually a good choice when changing the thing you are iterating
>> over. Basically, if you ever feel you need to do something odd with the
>> iterator that you are incrementing (or decrementing) - skipping the
>> increment, repeating it, or otherwise changing its value - then "for" is
>> unlikely to be the best choice of structure.
>>
> Arguably the overall "shape" of this loop is still a `for` loop: you
> still scan the list in order, and there's still a fixed increment step
> in the normal case. It's just that in the "marked" case there's a kink
> (in this example that's the entire body of the loop, but you could
> imagine a more complex function). It's open to interpretation though :)

I agree that these things are open to interpretation, and "arguable".
But I disagree in my interpretation :-)

Key features of a "for" loop, as I see it, are that the structure you
are looping over is not changed, the iterator progresses continuously,
and that the iterator is not changed other than by the third clause of
the "for" statement. Then you know exactly how the loop is looping by
looking at the "for" statement itself, rather than the contents of the
loop. (It's okay to "break" out of the loop early.)

C++ does not enforce these restrictions, but I think they are useful
guides for clear code. They follow a general pattern of changing things
in one place only, which makes it easier to know what is going on and
where variables are modified. (Modern programming languages often
default to immutable - const - variables unless you specifically choose
to make them mutable, precisely because it makes the logic of the code
clearer.)

To my highly subjective (obviously) eyes, the "while" loop accurately
represents the logic of the code, but your nested "for" and "while" (or
"for" with "repeat") seems needlessly convoluted.

Marcin's "eraseIf" has merits too, but IMHO it complicates a rather
simple task.

Anyway, the point is that there are various ways to write this kind of
thing in relatively clear and simple code without having to invent a new
"repeat" statement.

David

Received on 2026-11-17 15:32:27