5 ms·
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.
by hthh 11y ago
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.html#Integer_Types https://google-styleguide.googlecode.com/svn/trunk/cppguide....
- raverbashing 11y agoYeah 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
- detrino 11y agoI 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; ... }
- gohrt 11y agoThe 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.
- deleted 11y ago[deleted]
- detrino 11y agoI 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.
- stinos 11y agoHmm, 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.