EasyHack Suggestion: Use range based for loops

Stephan Bergmann sbergman at redhat.com
Thu Oct 21 16:15:49 UTC 2021


On 10/21/21 17:25, Luboš Luňák wrote:
> 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.

Maybe cut the complete easy hack description down to just "Use range 
based for loops ...where applicable, across the source code".  Those 
easy hacks are meant for people to start getting involved in LO 
development, not to teach people about C++ in general.



More information about the LibreOffice mailing list