Is it safe to assume that sizeof(double)
will always be greater than or equal to sizeof(void*)
?
To put this in some context, is the following portable?
int x = 100;
double tmp;
union {
double dbl;
void* ptr;
} conv;
conv.ptr = (void*)&x;
tmp = conv.dbl;
conv.dbl = tmp;
printf("%d\n", *((int*)conv.ptr));
It does work on the few machines that I've tested it on, but I can see this going horribly wrong if sizeof(void*) > sizeof(double)
.
On current systems yes. double
is 64 bits on all current and future systems because they're aligned with IEEE arithmetic's double-precision. It's unlikely but certainly possible that pointers could be larger in the future - probably not for the sake of larger address space, but instead for carrying with them bounding information.
In any case it seems like a really bad idea to rely on any relationship between double
and void *
...
The size has nothing to do with it. There will always be some bits stored in there and the size will always be large enough to hold a void*
. What will go wrong is that you interpret an almost random bit pattern as a pointer, this can't do much else than crash, but most probably you knew that already. Don't do it.
来源:https://stackoverflow.com/questions/11309273/is-it-safe-to-assume-sizeofdouble-sizeofvoid