Apparently unsigned types really are necessary

Jonathan M Davis jmdavisProg at gmx.com
Sun Jan 22 04:49:37 PST 2012


On Sunday, January 22, 2012 13:40:08 Marco Leise wrote:
> I heard that in the past, but in my own experience using unsigned data
> types, it did not cause any more bugs. OTOH, textual output is more
> correct and I find code easier to understand, if it is using the correct
> 'class' of integers. But this "a lot of programmers who don't particularly
> like using unsigned types" must come from somewhere. Except for existing
> bugs in the form of silent under-/overflows that do not appear alarming in
> a debugger due to their signedness, I've yet to see a convincing example
> of real world code, that I would write this way and is flawed due to the
> use of uint instead of int. Or is this like spaces vs. tabs? 'Cause I'm
> also a tab user.

Down with tabs! ;)

One issue with unsigned integers right off the bat is for loops.

for(size_t i = a.length; i > 0; --i) {}

is not going to work. Another potentially nasty situation is subtraction. It 
can do fun things when you subtract one unsigned type from another if you're 
not careful (since if the result is negative and is then assigned to an 
unsigned integer...). There are probably others, but that's what comes to mind 
immediately. In general, it comes down to issues with them rolling over and 
becoming incredibly large values when they go below 0.

Sure, unsigned types can be useful, and if you're careful with them, you can 
be fine, but there are definitely cases where they cause trouble. Hence, why 
many programmers argue for not using them unless you actually need them.

- Jonathan M Davis


More information about the Digitalmars-d mailing list