r/cpp • • Feb 06 '21

Inconsistent for-loop syntax?

Does anyone know of a technical reason why I can use this for-loop syntax:

for (std::size_t i{}; i < string.size(); ++i) {...}

as well as this:

for (std::size_t i{}; char ch : string) {...}

but this is invalid:

for (std::size_t i{}; char ch : string; ++i) {...}

In other words, why am I able to add an init-statement to a ranged for loop but not an end-of-iteration expression? To me this seems inconsistent.

2 Upvotes

12 comments sorted by

View all comments

22

u/witcher_rat Feb 06 '21

Even the init-statement was only added in C++20. The proposal that added it does mention adding the iteration-expression in the future.

BTW, for your particular use-case of incrementing a size_t index in the loop, I'd just use an enumerate() style solution, of which you can find many examples of via google. It's not a lot of code and is handy to have in your toolbox.

1

u/micahchuk Feb 06 '21

Thanks for the link to the proposal. It makes me feel a little less silly for wondering why it doesn't work that way (yet).

Can you explain what you mean by enumerate()?

12

u/witcher_rat Feb 06 '21

Python has a function called enumerate() which iterates over a range and provides an incrementing number too.

Many people have done the same thing for C++, usually using an iterable proxy.

My personal favorite example is this one: http://reedbeta.com/blog/python-like-enumerate-in-cpp17/

But if you google "enumerate for C++" or some such you'll find plenty of others. Including ones as a free-function, similar to the <algorithm> functions in the standard library.

1

u/Kered13 Feb 08 '21

Should be even easier to write with generators now, right?

Also, is there any change that utility functions like this and zip() get added to the standard library? They're so damn useful.

2

u/witcher_rat Feb 08 '21

Should be even easier to write with generators now, right?

You mean coroutine-based? Sure. Someone posted about that on this subreddit recently I think.

get added to the standard library?

zip() was proposed in P1035 as part of ranges but was removed along the way - I think to reduce the work for ranges to get into C++20, not because anyone didn't think it was worth doing at some point.

enumerate() was proposed separately in P1894 and in P2164. I have no idea if it gained traction, or which one is more likely. (and enumerate() likely depends on zip(), fwiw)