Casting Pointers?
Anon via Digitalmars-d
digitalmars-d at puremagic.com
Thu May 12 09:42:57 PDT 2016
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...)
This is a Bad Idea in C because types in C aren't actually
well-defined. `long` is required to be at least 32 bits. `double`
is required to be a floating point type. They will often not
match up in sizes the way you might think. The spec doesn't even
require `double` to be IEEE (that's an optional annex).
Clang on Linux x86_64 has both `long` and `double` as 64-bit
types.
Clang on Linux x86 has `long` as 32-bit, `double` as 64-bit.
> Is this legal / valid in D and if not what is the appropriate
> way to efficiently access data like this?
In D, both `long` and `double` are defined in the spec to be
64-bits, regardless of compiler/os/arch. It isn't "safe" (because
casting pointers is never safe), but it should behave predictably.
Note that D does have its own poorly-defined types, such as
`real`, that you will need to be careful with.
More information about the Digitalmars-d
mailing list