Casting Pointers?
John Burton via Digitalmars-d
digitalmars-d at puremagic.com
Thu May 12 03:26:42 PDT 2016
On Thursday, 12 May 2016 at 09:25:49 UTC, Stefan Koch wrote:
> On Thursday, 12 May 2016 at 08:41:25 UTC, John Burton wrote:
>> I've been unable to find a clear definitive answer to this so
>> please point me to one if it already exists in the manual or
>> the forums.
>>
>> Is it safe to cast pointer types?
>>
>> double data;
>> long p = *cast(long*)&data;
>>
>> (Excuse any silly syntax errors as I'm doing this on my phone).
>>
>> This used to be possible in C until people recently decided it
>> not only was wrong, it had always been wrong :P (Ok I'm not
>> entirely serious there but that's what this issue feels
>> like...)
>>
>> Is this legal / valid in D and if not what is the appropriate
>> way to efficiently access data like this?
>
> How would such a cast be safe?
"Safe" as in it produces a valid long value by interpreting the
bytes of the stored double. Obviously if it works it's very
system dependent.
But in C it's simply undefined behavior to read a value stored
using one pointer type using a pointer to a different type. (With
some additional rules about char in a few cases).
The whole strict aliasing businesss
More information about the Digitalmars-d
mailing list