logoalt Hacker News

AdieuToLogic • today at 2:25 AM • 1 reply • view on HN

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;
  }

Replies

i2talics • today at 2:58 AM

Most compilers will be able to optimize the index version into this.