C++20 Improved the For-Loop Syntax

jpmitchell1 pts0 comments

How C++20 improved the for-loop syntax How C++20 improved the for-loop syntax

Blog

Codex

How C++20 improved the for-loop syntax

Posted July 11, 2026 2 min read A small piece of syntactic sugar from C++20.<br>Let’s say I wanted to print out the following:1: the<br>2: quick<br>3: brown<br>4: fox<br>5: jumped<br>6: over<br>7: the<br>8: lazy<br>9: dogIf I had to use Python, I’d write something like this: 1vec = [<br>2 "the", "quick", "brown", "fox",<br>3 "jumped", "over", "the", "lazy", "dog"<br>4]<br>8for i, it in enumerate(vec, start=1):<br>9 print(f"{i}: {it}")<br>And if I were to use Lua, it might look like this: 1local vec = {<br>2 "the", "quick", "brown", "fox",<br>3 "jumped", "over", "the", "lazy", "dog"<br>4}<br>8for i, it in ipairs(vec) do<br>9 print(i .. ": " .. it)<br>10end<br>But if I were to use C++17 or older, the equivalent approach would look like this: vec = {<br>"the", "quick", "brown", "fox",<br>"jumped", "over", "the", "lazy", "dog"<br>};

for (int i = 0; i 1vectorstring> vec = {<br>2 "the", "quick", "brown", "fox",<br>3 "jumped", "over", "the", "lazy", "dog"<br>4};<br>8for (int i = 0; i vec.size(); ++i)<br>9{<br>10 auto&& it = vec[i];<br>11 cout i ": " it endl;<br>12}<br>The common theme of these examples is that they produce a for-loop that includes in its scope both an index value and element reference. C++ stands out for having to introduce the reference to it’s loop scope with an additional statement.With C++20, it is now possible to create an example that matches the other languages, and it looks like this: vec = {<br>"the", "quick", "brown", "fox",<br>"jumped", "over", "the", "lazy", "dog"<br>};

for (int i=0; auto&& it: vec)<br>cout 1vectorstring> vec = {<br>2 "the", "quick", "brown", "fox",<br>3 "jumped", "over", "the", "lazy", "dog"<br>4};<br>8for (int i=0; auto&& it: vec)<br>9 cout (++i) ": " it endl;<br>The specific proposal that enables this is called Range-based for statements with initializer, and it is very similar to a previous proposal from C++17, If statement with initializer. What I have demonstrated in this post is precisely the intended use-case for this language feature.I really like it. It may seem very trivial, but small pieces of syntactic sugar like this pay large dividends when used across an entire codebase. I’ve only just discovered it myself, but I intend to use it exclusively over the traditional approach going forward.It seems to me that the C++ Standards Committee is doing a decent job maintaining the language, and introducing useful features when it makes sense to do so. Have you discovered any small quality-of-life features such as this? If so, let me know!<br>Send a message to mail@lzon.ca, or DM me on one of my social accounts on the homepage.

Settings<br>Theme

Primary<br>Secondary<br>Tertiary

Secrets

quick brown jumped lazy loop like

Related Articles