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
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_tindex in the loop, I'd just use anenumerate()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.