Pragmatic Advice for C++11’s Range-For

C++ is known to be a programming language that offers several options for doing stuff, and with all the options available for range-based for loops, sometimes folks (especially beginners) get confused.

My pragmatic piece of advice for C++11’s range-based for loops is:

  1. If you are observing the items in the container, use “const auto&”.
  2. If you are modifying the items in place during the iteration, use “auto&”.

That’s as simple as that!

In code:

// Observe elements
for (const auto& elem : container)

// Modify elements in place
for (auto& elem : container)

A more detailed discussion can be found on StackOverflow (this includes also some special corner-cases, like proxy iterators as in std::vector<bool>, or auto&& in generic code):

“What is the correct way of using C++11’s range-based for?”

P.S.
I’ve also seen some code with const auto&& used in range-for, but that doesn’t seem to make sense.

2 Replies to “Pragmatic Advice for C++11’s Range-For”

Leave a Reply

Your email address will not be published. Required fields are marked *