r/cpp • u/micahchuk • 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
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.