Iterating Backwards in C

davidpriver.com

43 points by cremno 3 days ago


Joker_vD - 2 minutes ago

That's the price of innovation, I guess; before C invented its "for"-loop, other languages had their equivalents generally looking like this:

    FOR var = start [DOWN] TO end BY step DO ... END
No custom increment expressions, and "step" even usually was only allowed to be a constant (in which case, the language usually didn't have DOWN specifier and used the step's sign instead). Then Dennis Ritchie invented C, and ditched the traditional "do"-loop (Fortran called that DO loop; Algol called it FOR, but most people preferred the Fortran's nomenclature... until C came to dominate, but that wouldn't happen for yet another 20 years) in favour of his invention because he felt that easily iterating through linked lists or strings was a much more pressing concern:

    for(p=head; p; p=p->next) { ... }

    for(s=str; *s; s++) { ... }
kooi - 4 minutes ago

As long as you make sure the end points are valid, this is most intuitive for me. Just using i as a backwards step.

for (int i = 1; i <= N; i++) {

    array[N-i]

}
kenferry - 2 hours ago

I know it's "too clever", but if I'm writing code no one else will ever see,

  while (i --> 0) {
      // use array[i]
  }
easy to read (if not understand), and correct!
randomblock1 - 9 minutes ago

I thought most people used the explicit version:

  for (size_t i = count; i > 0; --i) {
      // use array[i - 1]
  }
You can also do something like:

  size_t index = i - 1;
to not have to use i-1. I believe the compiler optimizes that out anyway to be identical.
bugake - 35 minutes ago

For the uninformed: counting backwards in a for loop is faster because comparing an unsigned integer against 0 is generally faster than comparing it against any other value.

It also says not to use `for (i >= 0)` because any unsigned integer is >= 0, and the loop will never end.

AdieuToLogic - an hour ago

Why not use the C/C++ idiom of pointer math?

  _Bool find_last (size_t count, int *haystack, int needle, size_t *where)
  {
    for (const int *pos = haystack + count; pos-- != haystack;) {
      if (*pos == needle) {
        *where = pos - haystack;
        return 1;
      }
    }
    return 0;
  }
MaulingMonkey - 2 hours ago

I prefer:

    const size_t n = 10;
    for (size_t i = n; i --> 0;) {
        std::cout << i << "\n";
    }
abstractspoon - 3 days ago

I've been using this method for more than 30 years!

rpsworld - 2 hours ago

[flagged]

lanmu - an hour ago

[flagged]