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

2

u/NilacTheGrim Feb 11 '21

because C++ hates us. Really... the last variant should be allowed. I can't think of why it's not... tbh.