Reputation: 11
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. }
Upvotes: 0
Views: 660
Reputation: 22644
In your specific case, you should use the type which does not generate an implicit type conversion in this expression:
i < someThing.length();
i.e. you should use the exact type of someThing.length()
. Look at its signature and use its return type for your local variable i
.
Don't think of loop variables as something special. If you're working with length
, use the type of length
. Try to be as consistent as possible within your project, avoiding unnecessary type conversions.
Upvotes: 2
Reputation: 106244
Obviously you should use a signed type when negative numbers are involved - the interesting question is whether it's still good to do so when the value is known to be non-negative but clearly doesn't need the extra range the equivalent unsigned type offers.
There is no concensus. Some considerations:
the real-world import of some variables is inherently signed (e.g. a person's age), unsigned variables can encode/communicate that to a programmer reading the source code
I'm not aware of any compiler that warns if you pass unsigned types into functions expecting signed or vice versa; claims that the choice of type can enforce correctness are dubious
many compilers do warn if signed and unsigned types are compared
some specific variables/types in libraries are either signed or unsigned, and it may make sense to use the same types for variables interacting with them, ensuring the representable range is the same
code like while (n-- >= 0)
and abs(a - b)
may not do what's wanted given unsigned types, which is one reason to have a general preference for signed types
Upvotes: 0
Reputation: 1747
You should use a signed variable when the value can be negative.
A length should always be positive and is because of this usually represented with an unsigned
type. It is the consensus as far as I can see in the standard library and other big libraries (often named size_t
for example ).
It is better to use unsigned int
for i because in case the length is big you won't have overflow problems but usually it makes no difference.
Many compilers will also give you a warning if you compare a int
(signed) with and unsigned int
because of this issue.
Upvotes: 0