D equivalent of C++ reinterpret cast?
Ali Çehreli
acehreli at yahoo.com
Sun Sep 19 22:28:13 PDT 2010
Jonathan M Davis wrote:
> On Sunday 19 September 2010 17:07:38 bearophile wrote:
>> orgoton baberek:
>>> Use a union, which is the correct and safe way.
>> C standard say that's not safe. You can force that to be safe in
C-GCC if
>> you explicitly disable a compiler optimization. I think D docs don't say
>> anything about this. And Walter has said that regarding such things
D acts
>> as C. So I am not sure that will be safe in future D.
>>
>> Bye,
>> bearophile
>
> I'd have to go digging in old posts, but I'm pretty sure that that's
essentially
> how you're supposed to do it in D. I haven't ever done it because I
think that
> that sort of casting is pretty evil and only should be used as a last
resort,
> but I believe that unions are the correct way to handle it in D.
I remember being a part of a discussion where D'is unions were told to
be exactly the same as C's. That means, results of using a union is only
specified when it's used through one its members. Writing to one member
and reading from another is unspecified. It is clear that endianness and
padding should complicate matters.
But it's still used in C in low level code. That must be because
programs are not as portable as thought; and if they are, compile time
checks and macro magic are possible to obtain expected behavior.
Ali
More information about the Digitalmars-d-learn
mailing list