Is it safe to assume sizeof(double) >= sizeof(void

2019-06-05 12:53发布

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).

2条回答
Fickle 薄情
2楼-- · 2019-06-05 13:22

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 *...

查看更多
萌系小妹纸
3楼-- · 2019-06-05 13:25

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.

查看更多
登录 后发表回答