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

I disagree with it, but the Google C++ Style Guide offers the rationale you're looking for (under "On Unsigned Integers"): https://google-styleguide.googlecode.com/svn/trunk/cppguide....


Hmm, that seems a rather weak argument indeed? Purely anecdotical, but the number of bugs I'v seen which stem from using int and then failing to check if it is negative (followed by using it as index or converting to unsigned) by far outweigh the number of times I even saw the type of loop they mention as a con.


Yeah this doesn't convince me

The bug example there, sure, needs a signed type, so you can't blame the type for its wrong usage

I've had more bugs coming from using signed types that I'll not be bothered by writing 'unsigned' ever again


I disagree that a signed type is the correct solution to that, rather you need a while loop:

  std::size_t i = foo.size();
  while (i != 0) {
    --i;
    ...
  }


The point is that C int types are an unsafe mess, so it's better to have one simple rule than memorize all the corner cases and address them all the time.


I am addressing the specific example given by the Google style guide. The code for counting down using a signed integer as they do has more corner cases than the while loop I have shown. Using their way, you have to remember to subtract 1 from the size at the start and then use >= in the loop conditional. My way is just the inverse of what you do while counting up.

It's also worth pointing out the style of loop they give can't be used at all if you are counting down iterators or pointers instead of numbers.




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

Search: