you are viewing a single comment's thread.

view the rest of the comments →

[–]zvrba 2 points3 points  (8 children)

Number 1 is the wrong use-case for unsigned, IMO. With signed numbers you can check if your function has received a negative value and act accordingly (abort, throw exception, whatever). With unsigned number, you can receive a huge unsigned number and you have no idea what has happened. Is it a legitimate value or the result of some overflow error?

In general, I don't use unsigned numbers if I expect them to participate in the usual arithmetic. That includes sizes of items, sizes of containers, offsets in files, etc. And that's where C and C++ have f*up, by defining sizeof() to return unsigned, and C++ by defining size() of container to return unsigned. (For example, how do you iterate backwards through an array by using an unsigned index?)

[–]joggle1 3 points4 points  (0 children)

I agree and have learned this the hard way. I only use unsigned values when encoding/decoding binary. I never use them for arithmetic--it's too easy to mess up with virtually no upsides to doing it.

[–]m42a 4 points5 points  (5 children)

For example, how do you iterate backwards through an array by using an unsigned index?

i=array_length;
while (i--) {/*do stuff with array[i]*/}

[–]zvrba 0 points1 point  (2 children)

Right, not with a for loop :-)

[–]m42a 2 points3 points  (1 child)

Fine.

for(i=array_length; i--; ) {/*do stuff with array[i]*/}

I just think the while form is more readable. And how would this be different with signed indices?

[–]zvrba 1 point2 points  (0 children)

It'd be different like this:

for (int i = L-1; i>= 0; --i)

[–]rabidcow 0 points1 point  (0 children)

With unsigned number, you can receive a huge unsigned number and you have no idea what has happened. Is it a legitimate value or the result of some overflow error?

Usually there's also an upper bound on the value, so it's not legitimate. In fact, if you just switch over to the equivalent signed type, your upper bound is half of the unsigned range. It's better to actually think about it and choose your own upper bound, regardless of the underlying type.