标签云

微信群

扫码加入我们

WeChat QR Code

When is it appropriate to use an unsigned variable over a signed one? What about in a for loop?I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. for (unsigned int i = 0; i < someThing.length(); i++) {SomeThing var = someThing.at(i);// You get the idea.}I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems' part.


I found this helpful: codemines.blogspot.ca/2007/10/…

2019年07月20日50分54秒

I think this question is quite opinion based. The presented code will run in both cases just fine, so you can use both. Except for performance reasons (no answer actually deals with performance so far) it's just personal taste.

2019年07月20日50分54秒

Later in that thread, it's shown that unsigned is vastly superior for detecting overflow in untrusted inputs.Unfortunately, the proposed "answers" to the puzzle aren't all that great.Mine is template<size_t limit> bool range_check_sum( unsigned a, unsigned b ) { return (a < limit) && (b < limit - a); }If anyone has a similarly simple and straightforward answer using signed types, I'd love to see it.

2019年07月20日50分54秒

Only when you're dealing with the size of something in bytes.

2019年07月21日50分54秒

mk12 Standard Library containers expose the size_type member for counts of elements, not just bytes. It should be used instead of std::size_t where available, but it's inaccurate to imply that anything starting with size_t can only mean bytes.

1970年01月01日00分02秒