4 ms·
In that specific case I'd do the following: for (size_t i = n; i-- > 0 ;) ... Or count from `length` to 1, but subtract 1 in the loop body, or count up an
by operator-name 4y ago
In that specific case I'd do the following:
for (size_t i = n; i-- > 0 ;) ...
Or count from `length` to 1, but subtract 1 in the loop body, or count up and subtract the length in the loop body. Any modern compiler should be able to optimise these to be equivalent.
In the majority of cases, counting down is not necessarily. Nor is ordered iteration. Most languages have a `for each` style syntax that's preferable anyway.
- cylon13 4y agoAh yes, the goes-to operator -->
- tomjakubowski 4y agoAnd the wink operator, so the compiler knows you know the deal
- divbzero 4y agoOr alternatively: size_t i = length; while (i--) ...
- jecel 4y agoUnless I am remembering C wrong, this would work but the for (size_t i = length; i-- > 0 ; ) ... that several other people posted would not execute for index 0. Shouldn't it be this instead? for (size_t i = length; --i > 0 ; ) ...