Here's a small piece of syntactic sugar from C++20.


Let's say I wanted to print out the following:

1: the
2: quick
3: brown
4: fox
5: jumped
6: over
7: the
8: lazy
9: dog

If I had to use Python, I'd write something like this:

vec = [
    "the", "quick", "brown", "fox", 
    "jumped", "over", "the", "lazy", "dog"
]



for i, it in enumerate(vec, start=1):
    print(f"{i}: {it}")

And if I were to use Lua, it might look like this:

local vec = { 
    "the", "quick", "brown", "fox", 
    "jumped", "over", "the", "lazy", "dog" 
}



for i, it in ipairs(vec) do
    print(i .. ": " .. it)
end

But if I were to use C++17 or older, the equivalent approach would look like this:

vector<string> vec = { 
    "the", "quick", "brown", "fox", 
    "jumped", "over", "the", "lazy", "dog" 
};



for (int i = 0; i < vec.size(); ++i)
{
    auto&& it = vec[i];
    cout << i << ": " << it << endl;
}

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:

vector<string> vec = { 
    "the", "quick", "brown", "fox", 
    "jumped", "over", "the", "lazy", "dog" 
};



for (int i=0; auto&& it: vec)
    cout << (++i) << ": " << it << endl;

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.


Need an experienced and skilled dev for your next project? Or a consultant help with your growing IT needs? Feel free to reach out at mail@jpmitchell.ca. I'm currently available for work.