views:

146

answers:

3

let's rope I can make this non-sujective

Here's the thing: Sometimes, on fixed-typed languages, I restrict input on methods and functions to positive numbers by using the unsigned types, like unsigned int or unsigned double, etc.

Most libraries, however, doesn't seem to think that way. Take C# string.Length. It's a integer, even though it can never be negative. Same goes for C/C++: sqrt input is an int or a double. I know there are reasons for this ... for example your argument might be read from a file and (no idea why) you may prefer to send the value directly to the function and check for errors latter (or use a try-catch block).

So, I'm assuming that libraries are way better designed than my own code. So what are the reasons against using unsigned numbers to represent positive numbers? It's because of overflow when we cast then back to signed types?

+2  A: 

In the case of C & C++, a lot of the libraries existed before unsigned entered the language, so vanilla int was all that was available. Newer additions to the libraries will use unsigned types such as size_t.

In the case of .NET, there are languages (e.g. Visual Basic) that don't have the concept of unsigned integers (at least as language features -- they can of course use the System.UInt32, etc. types).

Niall C.
Good answer. I would only add to this that for core .NET methods there's no need to distinguish signed/unsigned as a type signature since this would add unnecessary complexity to languages that would otherwise just have an Integer/Numeric type.
Steve Dennis
Another point is that the .NET classes have bounds checking so that negative indices will cause exceptions.
Niall C.
In other words, do you believe I should use unsigned in other to avoid negative input in my function/methods?
Bruno Brant
Niall C.
A: 

I generally tend to go for int for loop iterators, unless I explicitly need large values (in which case size_t or ssize_t is probably an even better option given 64 bit architectures). Part because the unsigned is more typing work :) But also, when counting down:

for(unsigned int i=100; i>=0; --i) 
{
    printf("%i\n");
}

Guess what will happen :) Even though you don't expect negative numbers, you can't signal them either if they happen. Which is sometimes very unsafe.

wump
A: 

Just to correct one part of what you said: in C and C++, sqrt always takes a floating point type (float, double or long double), and the language doesn't include any unsigned floating point types. C99 adds csqrt to deal with the complex types, but these (again) are based on floating point types -- and since they deal with complex numbers, they can produce perfectly reasonable results from an input with a negative real part anyway.

Jerry Coffin