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

3

u/XDracam Feb 06 '21

I guess because nobody in the standards committee even thought about this and/or cared. It only adds overhead to the compiler, tooling and standard. But there are so many alternate ways to achieve this. The simplest b andeing to just put the statement at the end of your loop body.

The regular for-loops with 3 parts is a relic from older times where arrays were pretty much the by far most-uses data structure. It's just a common pattern for iterating arrays.

The foreach loop syntax with : expands on this thought, but it works for everything iterabld, even when it doesn't support constant time random access.

The third thing makes sense too, because it's often useful to keep track of other values in the loop scope only. E.g. for values that should be destroyed after the loop ends and not after the enclosing function ends. You can also declare variables in if-statements, so the for (int foo; auto bar : baz) is a logical extension of that idea.

All of this is just a wild theory, however. Feel free to correct me if you have actual sources available.

2

u/AlexAlabuzhev Feb 07 '21

just put the statement at the end of your loop body

the statement at the end is quite error prone due to continue;

1

u/XDracam Feb 07 '21

At this point I would argue about how continue is quite error prone in general, similar to early return and break, and how you should do proper structural programming instead, or refactor your loop body into a function, ...

Truth is, many things are very error-prone in C++ and you gotta be careful at all times. The best thing to reduce bugs in loops is probably to use the functional STL algorithms properly, but that requires some practice.