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

Steve Sobel via Digitalmars-d digitalmars-d at puremagic.com
Thu Nov 20 10:20:27 PST 2014


On Thursday, 20 November 2014 at 08:18:24 UTC, Don wrote:
> ...
>
> It's particularly challenging in D because of the widespread 
> use of 'auto':
>
> auto x = foo();
> auto y = bar();
> auto z = baz();
>
> if (x - y > z) { ... }
>
>
> This might be a bug, if one of these functions returns an 
> unsigned type.  Good luck finding that. Note that if all 
> functions return unsigned, there isn't even any signed-unsigned 
> mismatch.
>
> ...

I personally think this code is bad style. If the function 
requires a signed integer type, then `auto` with no 
qualifications at all is clearly too loose- if the programmer had 
specified what he needed to begin with, the error would have been 
caught at compile time.

You can replace `auto` with an explicit signed integer type like 
`long`. If foo and bar are template parameters and you don't know 
the precise return type, then a static assert that x and y are 
signed will do the trick.

If it is known that x > y and the function does not require a 
signed integer type, then an assert should be used.

Frankly that snippet just illustrates the sort of constraints 
that should be put on generic code.


More information about the Digitalmars-d mailing list