3 ms·
>I love for loops because in one line I can grasp what the loop intends to compute and usually leads me towards what I should pay attention to when debugging.
by BeetleB 8y ago
>I love for loops because in one line I can grasp what the loop intends to compute and usually leads me towards what I should pay attention to when debugging.
C++ programmer here.
In my team I've actively pushed not to have for loops when something from the algorithms library will do (transform, copy_if, find_if, etc). The reason: Because I usually cannot quickly grasp what the for loop intends to compute - I'm quite surprised you're saying the opposite.
I met with some resistance, as people aren't used to thinking in terms of algorithms. So I was slowly browsing our code base, finding for loops, and converting the trivial ones to calls to the algorithms library. Then I came across one for loop that was, frankly, a pointless loop. It didn't seem to do anything useful. I was sure it was a bug, but I couldn't tell from the context what the code was supposed to do. I emailed the committer, and he fixed it. Then I took the fixed version and converted it to an algorithms call.
Then I made a presentation to the team showing some of my examples, including the one with the bug. That bug convinced many to start using other constructs. Every time you write a for loop for which there is an algorithm in the library, you are reinventing the wheel, and have a good chance of introducing a bug.
(Sorry, probably a bit of a tangent to the whole thread).
- srean 8y agoVery true, wish your comment had more upvotes to bubble up to the top of the thread. Its a lot easier to miss edge cases, have off by one errors when one is manipulating iter count directly. Working with the abstraction natural to the problem reduces these. So manipulating /creating / merging rows, columns, blocks when working with arrays help avoid many of these problems. Usually the algorithm pseudocode is written in terms of such abstractions.
- RobLach 8y agoCompelling arguments here. What you’re saying is true in my experience as well in the cases you’ve explained.
- skgoa 8y ago> Because I usually cannot quickly grasp what the for loop intends to compute - I'm quite surprised you're saying the opposite. Yeah, a for loop breaks the relevant information up into several lines and depending on language it adds quite a bit of boilerplate.