C++20 Improves For-Loop Syntax with Cleaner Index and Element Access
C++20 Improved the For-Loop Syntax
I discovered a small but powerful C++20 feature that lets range-based for-loops include an initializer, matching the clean syntax of Python and Lua. This change eliminates the need for manual index management, making code more readable and reducing boilerplate. I plan to use this quality-of-life improvement exclusively going forward.
"It may seem very trivial, but small pieces of syntactic sugar like this pay large dividends when used across an entire codebase."
HN discussion
- Critics argue the new C++20 for-loop syntax is confusing because the variable name 'it' implies an iterator while actually holding a value, and the structure resembles two separate statements rather than a unified loop.
- Practitioners suggest that C++23's std::views::enumerate with structured bindings offers a significantly cleaner and more Pythonic alternative to the C++20 approach.
- Some developers contend that the standards committee is intentionally fragmenting C++ with half-baked features to sabotage the language and clear the way for Rust.
- WalterBright advocates for D's foreach syntax, which automatically adapts to arrays or ranges, as a more elegant and refactor-friendly solution than C++'s current direction.
- A minority of commenters reject modern C++ entirely, preferring C++98 or C-style syntax to avoid what they perceive as unnecessary complexity and 'monstrosities' introduced by recent standards.