To avoid some 32=>64 bit user code port bugs

bearophile bearophileHUGS at lycos.com
Mon Aug 16 07:40:15 PDT 2010


This shows many pitfalls regarding conversion of 32 bit code to 64, some of them are relevant for D code too:
http://www.gamedev.net/reference/articles/article2767.asp


On 32 bit D systems this compiles with no errors, while on 64 bit D this probably requires a cast:

size_t foo() { return -1; }
void main() {
    uint r = foo();
}

I'd like D to be designed to make 32=>64 porting as bug-free as possible, so dmd may guard against some possible 64bit troubles even if the code is compiled in 32 bit mode. So I think size_t=>uint may require a cast on 32 bit systems too, so when the code gets compiled with the 64 bit dmd this error isn't present.

---------------

With the 32 bit DMD this code works:

void main() {
    int x;
    int* ptr = &x;
    uint y = cast(uint)ptr;
    // ... usage of y
}


The cast() silences the compiler on 64 bit systems too, but on 64 bit systems this may be more correct:
size_t value = cast(size_t)ptr;

A cast() is a way for the programmer to express the desire to punch a hole in the type system, but in my opinion not all casts are equally unsafe. Some of them are _more_ bug-prone than others. On 64 bit systems a pointer=>uint cast is less safe than a pointer=>size_t cast or a pointer=>ptrdiff_t cast, because it's a lossless transformation.

(In practice I think that a pointer=>uint is a bad thing even in 32 bit code, when a sign is really necessary it's probably better to use ptrdiff_t on 32 bit systems too).

So 64 bit DMD may show a warning for pointer=>uint casts, I don't know.

Bye,
bearophile


More information about the Digitalmars-d mailing list