Re: Does standard say anything about pointer->int or int->ptr conversions?
On Monday, 5 August 2013 22:55:02 UTC+1, Ian Collins wrote:
Peter wrote:
It's not that uncommon to see code where integral type is cast to a
pointer or vice versa. On this page:
https://computing.llnl.gov/tutorials/pthreads/
you can see a few examples of casting void* to long, long to void*
etc. Does standard address such conversions in any way other than
calling them "undefined behaviour"? If not then why do people use
them? Are they well defined for a particular compiler/hardware?
Old (C) habits die hard!
Old (C) interfaces have a long life too. I've not looked at the
example he cited, but since it involves pthreads, I rather
suspect the casting is to pass an int as argument to the
callback (which formally takes a void*). It's one case where
I'll cast from int to void* and back. The alternative is to
pass the address of an int, and ensure that it will still be
accessible when the new thread gets around to reading it.
On most (if not all?) current 64 bit systems, a pointer is a quart to an
int's pint pot. In other words, it won't fit. A long is more likely to
be the same size as a pointer, but that's not guaranteed.
Note that in this case, you're starting with an int (and often,
with an int known to have a very small value). If void* is
larger than an int, that's no problem. (If int is larger than
a void*, it could be, if you needed all of the range of the
int.)
--
James