Hacker News new | ask | show | jobs
by AdieuToLogic 31 days 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;
  }
2 comments

Most compilers will be able to optimize the index version into this.
Isn't decrementing pos beyond start of haystack technically undefined behaviour?
It would be if pos were dereferenced in that state. However, since the postfix decrement operator is used in the inequality test, pos pointing to an undefined location is never used.