C++ Logo

std-proposals

Advanced search

Re: [std-proposals] for-loops revision (simplification and new syntax)

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 12 Feb 2025 09:46:11 +0000
On Wed, 12 Feb 2025, 02:42 Henry Miller via Std-Proposals, <
std-proposals_at_[hidden]> wrote:

>
>
> On Tue, Feb 11, 2025, at 12:03, Pau Miquel Montequi Hernandez via
> Std-Proposals wrote:
> > @Andrey Semashev
> >
> >> Quite honestly, looping with a counter is by far not the most common
> kind
> >> of loops you write in real code. It is the simplest kind of loop that
> they
> >> teach in clases
> >
> >
> > Looping with a counter might not be the most common kind of loop written,
> > but indeed it is the simplest kind of loop that they teach in classes.
> "*Make
> > simple things simple*" is a good principle that improves readability and
> > teachability of the language. Also this proposal can be seen as a way to
> > homogenize the loops, if something looks like a range, should be iterable
> > as a range; right now C++11's range-for loop is used for many constructs
> > that look and behave like ranges but leave aside the most simple of them:
> > just iterate from number A to nomber B, in my opiniĆ³n this is an
> oversight.
>
> many developes have adopted a no loops ever policy. It turns out everytime
> you think loop you can reach for std:: where you will find an algorithm
> that is more expressive and safer to get the same result. I'm not 100%
> there but I'm close.
>
> As such the only use I have for loops is teaching how things work inside.
> for students being explict about exactly what is happening is comforting
> even if most often the loop always looks the same. Perhaps the syntax could
> be improved but is it worth making it easier to use something rarely used?
>

Does adding several new ways to write a loop make things easier?

Especially when some of the suggestions add or remove parts of the usual
syntax. It seems to me that it would make it harder to read the loop header
because you'd have to examine it more carefully to see what it was doing
(especially the suggestion for multiple init statements).

And it's all just syntactic sugar, not enabling anything new which can't be
done (quite easily!) today.

The range-based 'for' loop added in C++11 actually enabled something new
which couldn't be done in C++03: iterating over arrays or containers with
uniform syntax, without needing to write 'typename R::iterator' or
'typename R::const_iterator'. And even that became redundant with 'auto'
and ' std::begin' added at the same time as the new 'for' loop.

Received on 2025-02-12 09:46:28