Hacker News new | past | comments | ask | show | jobs | submit login

Now i is no longer an index, it's index-plus-one.



Nope, 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
  }


No, 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.


> 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.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: