r/cpp • u/Clean-Upstairs-8481 • Mar 22 '26
[ Removed by moderator ]
[removed] — view removed post
51
Upvotes
r/cpp • u/Clean-Upstairs-8481 • Mar 22 '26
[removed] — view removed post
•
u/STL MSVC STL Dev Mar 22 '26 edited Mar 23 '26
Please post links as links, not as text posts.
Edit: Reposted as https://www.reddit.com/r/cpp/comments/1s0q8ig/c20_ranges_vs_traditional_loops_when_to_use/ . Removing and locking this one to avoid split discussion.
35
u/eyes-are-fading-blue Mar 22 '26
Ranges with c++23 help address some of the more verbose ways to write container population.
Views also help with some filtering or view composition like
zip_view.Furthermore, for not-so-out-of-ordinary data manipulation, it helps you write cleaner code.
In my experience, when you force ranges to your business logic which isn’t a common operation, say a work-around or some very specific thing, it makes the code more difficult to read and debug.
In general, ranges are harder to debug than range-based for loop but also you are less likely to make mistakes because it’s more expressive.
It’s hard to make a statement without seeing where and how you use it. I would definitely not force it because “it’s modern way to write code”.
14
u/Sensitive-Talk9616 Mar 22 '26 edited Mar 22 '26
The benefit of (C++23) ranges is that doing many common container operations becomes less wordy, more succinct, and more expressive. What you'd need to do in a for loop (with a chance to make off-by-one errors, overflows, etc.) you can do now with a single function call with, finally, a reasonable signature.
On the other hand, there may be a slight overhead compared to raw loops. But more importantly, I find complex range/filter expressions difficult to debug. Where you calculate, filter, sort, and reduce in one call. Maybe I'm just not used to it, skill issue.
I'd use them when you only need to do one or two things. If your loop calls for branching logic, has side effects, etc., it's probably clearer to do a for loop with properly named variables where you can just step through and understand where stuff goes wrong.
12
u/Specialist_Nerve_420 Mar 22 '26
just use whatever makes the code easier to read
3
u/Potterrrrrrrr Mar 22 '26
One of the nifty uses for me was making a bunch of forward ranges/iterators for a html node based structure, now I can use ranged for loops to loop over all the descendants of a node and also query things about a certain sub tree by using the range algorithms. Not exactly ground breaking but I found it pretty cool
-8
u/Charming-Work-2384 Mar 22 '26
Ranges work on containers.
Embedded... generally dont, due to code size restrictions.
Its better off with raw loops ...
That is my opinion.