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

13

u/HappyFruitTree Feb 06 '21

You should think of for(init;cond;incr) and for(decl:range) as two different types of loop. The former is a for loop and the latter is a range-based for loop.

In recent times the standard have added an optional init statement to if and switch statements so that you shouldn't have to declare variables outside the loop that are only used in the condition. This was also decided to be useful for the range-based for loops.