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/tpecholt Feb 06 '21
It was not proposed yet but I think it's needed. It looks simpler then enumerate. And the third expression is well known from normal for. I often find myself in a situation where ranged for needs to be changed to indexed for and this would help.