C++20 range based for-loop with initializer statement

Gajendra Gulgulia
3 min readJan 18, 2023

Range based for loop with initializer statements are to range based for loop in C++20 what if statements with initializer statements are to if-else in C++17. If you are Proponent of using clean C++ with modern syntax, then chances are high that the pre-C++20 version of range based for-loop must have limited you at some point.

This article is not about how range based for loop work, for which there are many discussions online including this SO post which goes into the verbose technicalities.

Range based for-loop before C++20

Range based for-loop were introduced in since C++11 and allowed iteration over a range of elements. One common use case is to iterate over the elements of a container

for(auto const& elem: elems){
//do something

It even allowed to capture multiple members in a container through structured binding

  for(auto const& [key, val]: map)
//do something

or iterate over elements in an intitializer list which is quite useful if the range is known in advance and one wants to limit the scope of the range to be iterated over.

  for(auto elem: {0,1,2,3,4,5,6,7,8,9})
//do something

and it even allowed the usage of attributes like nodiscard , maybe_unused since C++17

for([[maybe_unused]] auto const& [key, value]: map)
//do something only with key…

--

--