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

I find that most programs deal with values greater-than-or-equal-to zero.

-1 is very frequently used as a sentinel value. For example, counting backwards through the elements of some container:

    for (i = count - 1; i >= 0; --i)
        /* body */;
I've had plenty of bugs prevented by "comparison of signed and unsigned" warnings

You wouldn't have had these warnings, much less needed to pay attention to them, if you hadn't had to use unsigned types in the first place.

This conversation is much like those around GC. It's impossible to convince people labouring under tyranny they've learned to love without them experiencing a free life first. You just can't communicate it with words.



> -1 is very frequently used as a sentinel value.

I actually think these sentinels work quite nicely with unsigned.

   unsigned element_num;
   static const unsigned NO_ELEMENT = (unsigned) -1;
Yes, you need a cast, but it's just one place. From then on you can use a nice constant for your sentinel.

Also, your sentinel is more range-check safe then it would have been if it were an int (the classic "if (x < sizeof(arr)) arr[x] = 1;" issue again)

> For example, counting backwards through the elements of some container:

Ok, that is a fair point. Tat type of loop is easy to mess up with an unsigned type. Worse, gcc will only warn you if you compile with -Wextra which not everybody does.

Actually implementing the loop in a safe manner isn't really that hard though, of course:

   if (count > 0) {
      unsigned i = count - 1;
      do {
         /* body */
      } while (i-- != 0);
   }
Couple extra lines, true. I don't think it loses much clarity.

> For example, counting backwards through the elements of some container:

You missed my point. I mean warnings caused by "oops, that's not the variable I meant to compare with there"

It's a similar story with "const". One of the great side-benefits of using "const" consistently is that suddenly you find that the compiler starts catching more of your dumb mistakes ("oh I thought this was called like func(dest,src) but it's actually func(src,dest)" The moral is that "more info to the compiler" translates to "compiler notices a larger percentage of your dumb mistakes"

> It's impossible to convince people labouring under tyranny they've learned to love without them experiencing a free life first.

Melodramatic much?




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

Search: