Do most application developers use signed integers in places where they really mean to use unsigned integers? I do it all the time, so do my co-workers. I haven't seen a lot of other extensive codebases (other than the Delphi VCL) and examples on the internet usually use integer. Whereas the VCL developers use their own data types (which would be the most non-lazy way to go about declaring variables).
Something seems a little dreadful about code like this
TStuffRec = record
recordID : Integer;
thingID : Integer;
otherThingID : Integer;
end;
when it could be written as
TStuffRec = record
recordID : Cardinal;
thingID : Cardinal;
otherThingID : Cardinal;
end;
Functionally, these records almost always work the same (and hopefully will continue to work the same even in 64-bit Delphi). But very large numbers will have conversion issues.
But there are drawbacks to using unsigned ints too. Mainly stemming from how annoying it is to mix the two.
The real question is, is this a thing that actually gets thought about or included in best practices? Is it usually just up to the developer?
Best Answer
One reason why I don't use unsigned integer types all that much in Delphi is that they can create problems when mixed with signed integers. Here's one that bit me once:
I had
i
declared as an unsigned integer, (after all, it's an index into a list that starts at 0, it never has to be negative, right?), but whenList.Count
was 0, it would not short-circuit the loop as expected because0 - 1
evaluates to a really high positive number. Oops!Between the potential safety problems inherent in mixing signed and unsigned integers, and the range issues, (if you're going to need positive numbers larger than
high(signed whatever)
, it's quite likely that you'll also end up needing positive numbers larger thanhigh(unsigned whatever)
too, so moving up to the next larger size instead of switching from signed to unsigned of the same size is usually the correct action,) I really haven't found too many uses for unsigned integers when representing most data.