Hacker News new | ask | show | jobs
by jylam 987 days ago
It always startles me when the first (actually the second) example is bad:

  int do_indexing(int *buf, const size_t bufsize, size_t index) {
      if(index < bufsize)
        return buf[index];
      return -1;
  }
buf[index] can hold the value -1, as buf holds signed ints, so that (corrected, by the author) function is totally wrong anyway.
1 comments

Without knowing the context and purpose of the function, which the author doesn’t state, it could actually be perfectly sensible. For example, -1 (or any negative int value) could be used to mark unused entries in the array, and entries beyond the current array size are simply unused by definition.