3 ms·
for( size_t i = x.size(); i-- > 0; ) ...
by Aldo_MX 12y ago
for( size_t i = x.size(); i-- > 0; ) ...
- delinka 12y agoNow i is no longer an index, it's index-plus-one.
- Aldo_MX 12y agoNope, it's still an index, after the comparison and before executing the code inside the loop, i is decreased by 1. Remember that a for loop does something like this behind the scenes: size_t i = x.size(); while( i-- > 0 ) { // your code which needs backwards iteration here ; // do nothing because there is no third statement }
- shdon 12y agoNo, it's not. The check is done before the loop, so i has the correct value inside the loop. Still, the trick makes it look suspect and that's an argument against using it.
- Aldo_MX 12y ago> Still, the trick makes it look suspect and that's an argument against using it. This is true. The code is confusing to people not used to it. A workaround could be to hide this code inside a macro, so people not interested in digging into the code would take the macro's word: #define REVERSE_LOOP( x, i ) for( size_t i = x.size(); i-- > 0; ) But unfortunately, that doesn't help with the fear that people has against unsigned types.