The example is doubly bugged.
i>=0 is never false. And if size is 0 it size-1 overflows leading to max value for the uint.
The correct way would be.
for(std::size_t i = vec.size(); i-- > 0;)
I guess the point being made is that with traditional loops, you can do the wrong thing but the pattern looks good at first glance because it has all the similar patterns of something that might be right when iterating forwards. And it hopes
to solve the same ambiguity with indexes as range based for loops did with iterators.
But again, this seems solvable without needing to add a new for loop syntax.
You could define something like:
for(size_t index: integer_interval(0, vec.size()))
Or
for(size_t index: reverse_integer_interval(vec.size(), 0, 1))
Where "interval" is not a list of all possible indexes, but 2 numbers (start and 1 past last) that gives an iterator that counts numbers in that interval.
Would this solution work?
Hi Simon,
could you shortly explain the possible bug in the example given?
To get the boundaries of size-1 and the >=0 correct or to avoid unsigned integer underflow?
auto leads to unsigned and size is 0?
-----Ursprüngliche Nachricht-----
Von: Simon Schröder via Std-Proposals <std-proposals@lists.isocpp.org>
Gesendet: Fr 14.02.2025 06:52
Betreff: Re: [std-proposals] for-loops revision (simplification and new syntax)
An:
std-proposals@lists.isocpp.org;
CC: Simon Schröder <dr.simon.schroeder@gmail.com>;
Some of the discussion now steered towards: “Is a new loop syntax useful?”
I would prefer a syntax that leverages the existing range syntax (something similar to Rust or Swift). There is probably one case where such a new syntax would help avoid bugs:
for(std::size_t i = vec.size()-1; i >= 0; --i) …
i.e. counting down a loop with an unsigned integer. This might be obfuscated a little more if one uses ‘auto’ to declare the loop counter. With a new syntax (that also allows to specify the step size and the step size can be negative) the implementation
would hopefully fix this edge case.
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals