'int' is enough for 'length' to migrate code from x86 to x64

Marco Leise via Digitalmars-d digitalmars-d at puremagic.com
Fri Nov 21 10:01:00 PST 2014


Am Fri, 21 Nov 2014 16:32:20 +0000
schrieb "Wyatt" <wyatt.epp at gmail.com>:

> Array lengths are always non-negative integers.  This is 
> axiomatic.  But the subtraction thing keeps coming up in this 
> thread; what to do?
> 
> There's probably something fundamentally wrong with this and I'll 
> probably be called an idiot by both "sides", but my gut feeling 
> is that if expressions with subtraction simply returned a signed 
> type by default, much of the problem would disappear. [...]

As I said above, I always order my unsigned variables by
magnitude and uint.max - uint.min should result in uint.max
and not -1. In code dealing with lengths or offsets there is
typically some "base" that is less than the "position" or an
"index" that is less than the "length".

The expression `base - position` is just wrong. If it is in
fact below "base" then you will end up with an if-else later
on under guarantee. So why not place it up front:

if (position >= base)
{
    auto offset = position - base;
}
else
{
    …
}

> [...]
> 
> -Wyatt
> 
> PS: I can't even believe how this thread has blown up, 
> considering how it started.

Exactly my thought, but suddenly I couldn't stop myself from
posting.

-- 
Marco



More information about the Digitalmars-d mailing list