Mixing operations with signed and unsigned types

Stewart Gordon smjg_1998 at yahoo.com
Thu Jul 8 10:37:05 PDT 2010


Ellery Newcomer wrote:
> On 07/06/2010 07:05 PM, Stewart Gordon wrote:
<snip>
>> Just using uint, of course!
> 
> For enforcing a non-negative constraint, that is brain damaged. 
> Semantically, the two are very different.

So effectively, the edit wars would be between people thinking at cross 
purposes.

I guess it would be interesting to see how many libraries are using 
unsigned types wherever the value is semantically unsigned, and how many 
are using signed types for such values (maybe with a few exceptions when 
there's a specific reason).

> int i;
> assert(i >= 0);
> 
> says i can cross the 0 boundary, but it's an error if it does, i.e. 
> programmer doesn't need to be perfect because it *does get caught* 
> (extreme instances notwithstanding).

Or equivalently,

uint i;
assert (i <= cast(uint) int.max);

> uint i;
> 
> says i cannot cross the 0 boundary, but it isn't an error if it does. 
> programmer needs to be perfect and error doesn't get caught (unless what 
> you're using it for can do appropriate bounds checking).

Or the wrapping round is an intended feature of what you're using it for.

>> Comparison - how do you mean?
>>
>> Stewart.
> 
> Mmmph. Just signed/unsigned, I guess (I was thinking foggily that 
> comparison intrinsically involves subtraction or something like that)

But whether subtraction for comparison works doesn't depend on whether 
the legal ranges of the source values are signed or unsigned, at least 
as long as they're both the same.

What it does depend on is whether the subtraction is performed in more 
bits than the number required to represent the legal range.

Stewart.


More information about the Digitalmars-d-learn mailing list