r/cpp • u/Vultrao • Jun 22 '21
[Belay the C++] Don’t use raw loops
https://belaycpp.com/2021/06/22/dont-use-raw-loops/21
u/Pragmatician Jun 22 '21
I agree with the sentiment, but Sean Parent didn't say "no raw loops" is a rule, but a goal. In reality, a normal loop can often be more readable than an algorithm. Also, pulling in big headers is an important consideration, not to mention <algorithm> becomes 2x bigger in C++20.
2
u/Vultrao Jun 22 '21
It is written in the article, black on white, "This statement is not an absolute, but an ideal to keep in mind when you code."
9
u/junkboxraider Jun 22 '21
And yet the title, “Don’t use raw loops” is an absolute. Do you expect people not to read that?
2
u/Vultrao Jun 22 '21
I expect people to read the whole thing, actually. Of course the title can't summarize the 1.2k words of the article.
13
u/junkboxraider Jun 22 '21
Fine, but your title is much more prescriptive and reductive than your whole argument. What’s the value in tilting everyone’s first impression that way?
The title could be “Avoid raw loops” and it would be just as short and more in line with the full post.
1
4
Jun 22 '21
You surely have struck a nerve here...
1
u/Vultrao Jun 22 '21
Sorry about that. It just feels like that sometimes people comment on an article without even reading it.
3
Jun 22 '21
I mean the topic in general. Tell people that for-loops are problematic at least, and you question their whole upbringing as a developer or programmer. Suggest to maybe adjust teaching and teach for-loops after the basic algorithms, and suddenly, you get dozens downvotes...
2
10
u/austinwiltshire Jun 22 '21
I often lose this argument when for_each is involved. A new style for each loop built into the language, to, for example, call a mutating member function on each member of a vector, ends up looking syntactically cleaner than std::for_each with member function pointers.
Similarly, passing a lambda into std::for_each ends up looking almost exactly like a new style for each, with no benefit in readability.
While I think consistency has some merit to it, this counter example is almost always used as a wedge issue in arguments I've been in to imply the always-use-algorithms camp is dogmatic.
Tangentially, one thing that is hilarious in this thread is people aghast that c++ newbies might try to use algorithms instead of raw loops. To me, that's exactly the right thing for them to do. Raw loops are more powerful and more advanced. If I see a raw loop, I'd prefer it come from an expert, not a novice.
5
u/Vultrao Jun 22 '21
I strongly agree about for_each. I mentioned it because it's one of the most basics, but I quite never have to use it.
I also agree that newbies should learn algorithms before raw loops.
4
Jun 22 '21
Did you see Kate Gregory's talk about stopping to teach C? I think this is exactly what she was referring to...
4
Jun 22 '21
I understand what the article wants to say. But it is just the noobs are gonna come and start with this. Based on my experience, I think I have learned about c++ using just the core features. Now that I am comfortable, I can use stdlib features more comfortably and appreciate them.
4
u/Vultrao Jun 22 '21
I really think that new people should learn the language top-bottom, unlike we did in the past. Unlike in the past, it is now better to write intentions in higher abstractions than just tons of basic low-level instructions.
It's an overhaul feeling that many agree about, for the times I went to C++ conventions and talked about this subject.
16
u/Glinren Jun 22 '21
reasons why I usually don't use std::algorithm:
they are clunky and I don't find them easier to read than loops:
std::vector<int> output_vector{}; std::transform( input_vector.begin(), input_vector.end(), std::back_inserter(output_vector), [](int i){return i*2 ;}); return output_vector; }
vs:
std::vector<int> mult_by_2(const std::vector<int> input_vector){
std::vector<int> output_vector{};
output_vector.reserve(input_vector.size());
for (const int element : input_vector){
output_vector.push_back(elem*2 );
};
return output_vector;
}the transform version is not really simpler than the loop version, I would argue that std::back_inserter adds cognitive load, with the indentation needed to make it readable it is as long if not longer than the loop version, and does std:transform reserve? I would be surprised if it did.
2. it doesn't support iterator chaining. that means i have to materialize every intermediate.That's a dangerously close to premature pessimization for any composed algorithm. It also means I lock myself into the container that are being passed around. Thankfully ranges seems to solve that issue and with the inclusion into the stl it hopefully gets better documented.
3. It rarely has the algorithm I want and making it do what I want makes the code hard to read. as an example: I needed to find an element conforming to a special predicate and check that it is unique: return a pointer to it if found, return an empty optional if not, throw if more than one such element is found:
auto first_it = find_first(vector.start(), vector.end(), predicate);
if(first_it == vector.end()){
return std::optional<T>{};
} else {
auto second_it = find_first(first_it, vector.end(), predicate);
if(second_it!= vector.end()){
throw ReplicatedElementException{};
} else {
return std::optional<T*>{&(*first_it)};
}
}the loop version:
std::optional<T* > found_element{};
for(auto & elem; vector){
if(predicate(elem)){
if(found_element.has_value()){
throw ReplicatedElementException{}
} else {
found_element = &elem;
};
};
};
return found_element;Whenever I try to use std::algorithm the code becomes more complicated, less flexible and reader needs more knowledge to understand it.
3. I don't use parallel execution policies. In the programs I write no single operation is important enough to let it wreak havok with my threading policies. I would prefer OMP before execution policies.
4. when working with 2 dimensional objects std::algorithm is just the wrong tool.
Conclusion: Apart from the sorting algorithms and occasionally std::accumulate nothing in std::algorithm is interesting enough to justify the complexity it introduces into the code.
5
u/Supadoplex Jun 23 '21 edited Jun 23 '21
How about ranges?
auto mult_by_2 = [](auto elem){ return elem * 2; }; auto result = input_vector | ranges::views::transform(mult_by_2) | ranges::to_vector;2. Can you explain the "locking yourself to the container" by using standard algorithms?
3. Your chosen design doesn't fit well with the standard algorithms. Why not follow their convetion, and return the iterator itself, end in case of not found? In case that's not feasible, you can still do it, and call the algorithm style function internally within the custom logic:
// reusable auto find_two(auto&& range, auto&& predicate) { auto begin = std::begin(range); auto end = std::end(range); auto first = std::find_if(begin, end, predicate); auto second = first == end ? end : std::find_if(std::next(first), end, predicate); return std::make_pair(first, second); } // custom logic auto [first, second] = find_two(container, predicate); if (first == container.end()) return std::nullopt; else if (second == container.end()) return &*first; else throw ReplicatedElementException{};These points aside: I agree that sometimes a loop can be fine. "Don't use raw loops" is like "Don't use goto": Sure, you can always avoid a raw loop just like you can avoid a goto, and often it's better to do so. But it's not better always.
2
u/adpirth Jun 23 '21
The ranges example looks definitely cleaner, but I have no idea how it's working under the hood. Also storing the result of a "binary OR" on a container, a function and whatever type ranges::to_vector is, into an auto type, just feels like a completely different language from C++.
3
u/Supadoplex Jun 23 '21
The ranges example looks definitely cleaner, but I have no idea how it's working under the hood.
You don't need to know :) What is important is to understand the result, which to me is clear.
Also storing the result of a "binary OR" on a container
Yeah, it's an unfortunate limitation of C++ that there is no way to define new operators (compare with Haskell for example where it is possible), which leads into this state of overloaded operators.
The concept of overloading should be familiar to C++ programmers because
*is both indirection and multiplication,&is both bitwise-and and addressof (not to mention their meaning as pointer and reference),<< >>are both bit-shifts and stream insert/extract,[]is both pointer arithmetic and map lookup etc.This new operator overload idiom is familiar to many (although probably not all) from shell languages where the "pipe" is used to redirect output of a program into another. I suspect that this was the inspiration.
4
u/adpirth Jun 23 '21
You don't need to know :)
If this was Python I'd agree with you, but I usually use C++ for embedded or time sensitive programs. Both fields could definitely profit from readable code and code reuse, but in both I need to know how it's working, at least broadly (are there allocations, what's the memory layout/footprint, will this result in a copy)
The concept of overloading should be familiar to C++ programmers
Sure but usually it's either similar in what it does, used in a completely different syntax, or has been in the language for ever.
Whereas
auto result = input_vector | ranges::views::transform(mult_by_2) | ranges::to_vector;at first glance looks very similar to the ORing of configuration values to store in a register, yet does something completely different. If they wanted to express a flow, a stream like syntax might have been easier to grasp for me.
1
u/RishabhRD Jun 23 '21
This example shown should be answered by someone for sure. It would be so good to learn.
22
u/scrumplesplunge Jun 22 '21
You can often use algorithms instead of raw loops, and in many cases it's a much better fit and even helps you to identify the edge cases that you might have forgotten otherwise.
That said, pre c++20 ranges, algorithms are hard to compose and can sometimes be a bit awkward compared to the raw loop equivalent. On top of that, raw loops are much nicer to debug in gdb. Ranges will help with the former but not really with the latter.
I think the focus should be more on reuse. If there's a nice packaged algorithm that does exactly what you want, don't reimplement it, but at the same time don't just shoehorn something into ranges just to avoid a raw loop.
44
u/avdgrinten Jun 22 '21
Like many of these "best practices" blog posts, this is wrong when taken as absolute truth. IMHO this kind of advise is even dangerous because junior developers will take it for granted when they read it on /r/cpp.
There are many situations where a raw loop expresses intent most clearly. Raw loops should absolutely be used in these cases.
STL algorithms are great for transforming data but not all loops transform data.
16
u/Full-Spectral Jun 22 '21
It's often just easier and cleaner to use a loop. It can be a ranged for loop, of course, which just isn't at all dangerous and doesn't require a lambda and a bunch of captures and such.
And often just an indexed loop is easiest. I often use enums for indices, so I need to have the enum value in the loop without a bunch of silly casting.
'Modern C++' can sometimes be a bit of a cargo cult.
7
u/manphiz Jun 22 '21
IMHO I would suggest trying to learn about STL algorithms and replaces raw loops as many as possible, as the STL algorithms provides at least the following benefits:
Make the intent clear: you know what you are doing by looking at the name of the algorithms, be it a transform, accumulation, predicate, etc. For raw loops you need to read the code to understand the intent. And there are many real-world code with loop bodies that are over 100 LOC, which will make this process less desirable.
If you roll your own implementations you are subject to subtle bugs or suboptimal code: did you accidentally moved reused data? Is there any unnecessary copy when a move is better? Did you try to do a transformation but accidentally performed an accumulation? Did I try to check for all_of but the code was actually checking for any_of? Using an algorithm will make those less likely to happen.
Since C++17 the first parameter of many algorithms can control whether the operation can be parallelized, so you can transform your loop to run in parallel by just adding an argument. Migrating your raw loop will be a much involved process.
Of course raw loops still have their uses, but mainly for legacy code or C-style data structures that you have to access by index. I would imagine with ranges the necessity will be even lower.
4
u/NilacTheGrim Jun 26 '21
Since C++17 the first parameter of many algorithms can control whether the operation can be parallelized,
Not on every compiler though. MSVC was the first to implement this feature, and gcc only after gcc-9. clang still doesn't have this and clang is being used a lot by a lot of people. The code I write has to run on macos, for example, and has to be buildable on a vanilla macos system with just Xcode installed....
Make the intent clear: you know what you are doing by looking at the name of the algorithms, be it a transform, accumulation, predicate, etc.
Sure, this is when named algorithms shine. If your loop matches an existing named algorithm, then it makes sense in that case to use the named algo.
Of course raw loops still have their uses, but mainly for legacy code or C-style data structures
Uh.. no. Hardly.
5
9
u/LeoPrementier Jun 22 '21
This sounds more like: extract code to functions and give them meaningfull names.
Raw loops are essential. Also for begginers, here is a way to execute something several times.
Algorithems are really not the full set of raw loops usage and ignoring this fact will just cause you to write more unreadable and useless code.
This is specially the case on other languages where the semantic of iterators is cleaner.
6
Jun 23 '21 edited Jun 23 '21
Why are they trying to push STL algorithms so hard?
Where I need C++ is writing low level simple code to render things, calculate math etc.
If I have [0..4] int indexes, what is a better way to count them? Iterators?
Sorry but for me, stuffing C++ code with high level abstractions just for abstractions makes using C++ pointless, we have better languages to code on high level which works great.
PS "Article has Category: bad practice" so true.
4
u/jk-jeon Jun 22 '21
My conclusion:
Use STL algorithms if it is immediately obvious how to achieve the goal with STL algorithms. Otherwise, just write raw loop.
After writing it with raw loops, think once more if it could be done simpler with STL algorithms (and google to see if I missed something), and if that's the case, rewrite it.
Funnily, as a result, I don't use STL algorithms much.
Really, STL algorithms are often not so versatile, and even when they are, the flexibility they offer often just makes them even more difficult to comprehend than raw loops.
They are useful only for tasks that they are designed to solve (which cover probably way smaller set of tasks than one might expect, while at the same time surprisingly larger than some others might think), but not others. So I think it is worth to keep learning them, but "don't use raw loops" seems like a pointless advice.
I mean, I know that the intention is not to shit on raw loops like zealots and advocate to use STL algorithms absolutely everywhere, but my point is that the tone is still too strong. A much better advice might be something like "prefer to use STL algorithms over raw loops whenever appropriate".
2
u/NilacTheGrim Jun 26 '21
I think this is good advice and generally what I try to do. I use stl algorithms only when they actually lead to simpler looking and easier to read code. If I have to jump through hoops with syntactic noise to use them, when the raw loop would be far cleaner, I use the raw loop.
And yes, some loops just have no algo that matches and
for (auto & thing : collecton) {is a LOT cleaner thanstd::for_each(collection.begin(), collection.end(), [&capture1, &capture2](auto &thing){ .... }));any day of the week.
4
Jun 22 '21
I don’t think its cut and dry if an algorithm is superior to a raw loop in all cases. The loop can sometimes be more flexible and peformant than the algorithms if you start having to introduce too many objects and and abstractions.
2
Jun 22 '21
Can I just add: I really don't like the tone of this discussion. I would have expected this kind of behavior on Facebook, not here. A few people who have commented should clearly think before posting.
Or maybe just: "You kiss your Momma with that mouth?"
1
-5
Jun 22 '21
Agreed, in my opinion, a raw loop is superfluous/verbose and doesn’t immediately show the intention of the piece of code while find/find_if and whatnot does
-8
Jun 22 '21
This cannot be stressed enough.
I am wondering: Are there teachers out there who move for-loops all the way to the end of their course, and begin with algorithms?
13
u/Pragmatician Jun 22 '21
Why would you move a fundamental control flow construct to the end of the course? Do you think it's easier to explain to a beginner what iterators, predicates and callback functions are?
-2
Jun 22 '21
Quite frankly: In many disciplines, teaching begins with common ideas and then goes deeper from there. We learn Newtonian mechanics before quantum theory. We learn adding small integers before even looking at fields and rings and all that. You can stop learning when you believe you know enough. If you're more curious, you stay in school until you have a PhD in ${SOME_OBSCURE_FIELD}. If you're yet more curious, you stay in academia and dig even deeper until you find the holy grail.
This just works. That is why I believe the bottom-up approach is just wrong and always has been.
8
u/tjerzyko Jun 22 '21
If you learn programming, first you need to learn how to read code, then how to write it. Without knowing what is "for", you are completely lost.
2
Jun 22 '21
Is that so?
How come physics and mathematics go the other way without problems? How come they have done so for centuries?
I strongly disagree.
5
u/InKryption07 Jun 22 '21
I would argue that mathematics doesn't necessarily "go the other way". There's a lot of different fields in math, and many derive various concepts from eachother, so it's more like maths just starts at the most easily conceptualized parts, with no real "top" or "bottom". Physics is definitely top-to-bottom though
At any rate, I personally think there's no "wrong way" to learn something. For me, personally, I couldn't "get" programming until I really started getting into lower level languages, and then worked my way up. But for many others the opposite is true. The main problem here is the erroneous attempt to "standardize" learning (in programming, and also just in general for a lot of subjects).
3
Jun 22 '21
Maybe no wrong way, but I see a tendency to cling to old concepts, trying desperately to find arguments against it.
I could imagine that teaching software development top-down could move us forward.
4
3
u/Full-Spectral Jun 22 '21
That would be just wrong, IMO. The big bag o' algorithms is more about professional slash business requirements than about understanding fundamental software concepts.
3
Jun 22 '21
Not necessarily.
I think the important thing in today's teaching is that people finally learn to write "what" and now "how". Write "I need the maximum from that list" and not "iterate over the list and store the element if it is larger than whatever is in this variable". That we don't write "divide that list by the maximum value", but "normalize the list". The we write code for people to read.
Don't under-estimate the algorithms.
3
u/Full-Spectral Jun 22 '21
I would very much disagree with that. That's the equivalent of the phone support guy with a flow chart of responses. The important thing at that point isn't writing code for people to read, it's learning the concepts that underlying everything we do.
It would be no different from any other sort of endeavor. When learning the violin, you have to learn the basics. It's not going to be something that anyone wants to hear, because that's not what's important at that point. It's about the growth of the violinist and the mastery of concepts and techniques. The people who will consume the violinist's output are a distant concern at that point.
0
Jun 22 '21
[deleted]
1
u/fire_p123456 Jun 22 '21
That’s only when you have only one partner….. see the uselessness of the statesmen now?
21
24
u/witcher_rat Jun 22 '21
There's so much wrong with this example in the post:
First off, you're setting
max_element = lastand then dereferencing it in the loop's body. Bad mojo.Secondly, the return value is
boolwhich is wrong.Thirdly, you're taking
Pred predby-value, which as far as you know could be an expensive function object to copy, or not even copyable. (and yes I know the<algorithms>do it too - they're wrong)