Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'm curious, what's wrong with size_t loop indices? I always thought that was the most correct type for the job


It's fine until you do almost any arithmetic using the index. Unsigned arithmetic is rarely what you want, and it quietly converts all of your signed types to unsigned giving you large positive values instead of small negative ones. Maybe this isn't a common use case for most people, but it came up all the time when I was doing signal processing algorithms.

Using ssize_t is pretty reasonable, and you're not going to overflow ssize_t for loop indices except in some very pathological cases on a 32 bit architecture.

If the arithmetic argument doesn't convince you, here's another one: write a correct loop (using size_t) which traverses your array in reverse order. Here is a broken example which would be fine with ssize_t:

    for (size_t ii = len - 1; ii >= 0; --ii) {

    }


A modern compiler would warn about the condition (ii >= 0) being always true.

One correct way would be

  for (size_t i = len; i > 0; --i) {
     // use i-1 as the array index
  }
or,

  size_t i = len
  while (i-- > 0) {
    // use i as the array index
  }


Can you not do: for (size_t i = len-1; i < len; i--)? Isn't -1 defined to be the largest integer that the unsigned type can handle?

Edit: I guess that wasn't the point of your example (that it may not be easily recognisable as a bug?)


Yeah, that works, but it's going to confuse more than half the people who ever look at it.




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

Search: