EasyHack Suggestion: Use range based for loops

Luboš Luňák l.lunak at collabora.com
Thu Oct 21 15:25:13 UTC 2021


On Thursday 21 of October 2021, Hossein Nourikhah wrote:
> Since C++11, range based loops are available for iterating over a known
> range of values. For example, when there is a need to process elements
> of a container, range based loops are usually a good choice. They are
> easy to write, read and understand.
>
> The simplest form is as below:
>
> for(auto variable : range)
> 	statement;

 I generally dislike the (ab)use of 'auto' to save a little typing at the 
expense of readibility. Code is read much more often than written, and it's 
also quite often read e.g. in gerrit where there's nothing to easily tell 
what 'auto' is, so generally code should be aimed at being easy to read, not 
necessarily to write. It's not black or white of course, but I disagree with 
something that generically advises to use 'auto'.

> Range based loops can simplify the code, but there are limitations for
> them. For example, if there is a need not to iterate over certain
> values, std::ranges::views::drop (C++20) should be used, so they are not
> suitable for replacing every normal for loop.

 If the instructions are aimed at people who need spelling out how to use 
ranged for loops, then it needs to stress more that it is basically usable 
only for sequential iterating over elements of a container that does not 
change. Otherwise we risk that newbies will break things by rewriting even 
non-trivial loops.

 And that std::ranges::views::drop part does not belong there at all. C++20 
makes it useless for now, and even without that it would only confuse people.

-- 
 Luboš Luňák
 l.lunak at collabora.com


More information about the LibreOffice mailing list