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
1
u/[deleted] Apr 02 '21
What a nightmare. Didn't even know that was in the language.
Having programmed a lot of perl, I always felt the 2nd style of loop should have been called foreach.
I would hate to run into this when reading someone's code.
Maybe they should add a 4th parameter to for, which works like a finally {} block in Java.
I'm still waiting for a ranged for: for (obj.begin() to obj.end())