What is the use of intptr_t?
I know it is an integer type that can be cast to/from pointer without loss of data, but why would I ever want to do this? What advantage does having an integer type have over void*
for holding the pointer and THE_REAL_TYPE*
for pointer arithmetic?
EDIT
The question marked as "already been asked" doesn't answer this. The question there is if using intptr_t
as a general replacement for void*
is a good idea, and the answers there seem to be "don't use intptr_t", so my question is still valid: What would be a good use case for intptr_t
?
The primary reason, you cannot do bitwise operation on a void *
, but you can do the same on a intptr_t
.
On many occassion, where you need to perform bitwise operation on an address, you can use intptr_t
.
However, for bitwise operations, best approach is to use the unsigned
counterpart, uintptr_t
.
As mentioned in the other answer by @chux, pointer comparison is another important aspect.
Also, FWIW, as per C11
standard, §7.20.1.4,
These types are optional.
There's also a semantic consideration.
A void*
is supposed to point to something. Despite modern practicality, a pointer is not a memory address. Okay, it usually/probably/always(!) holds one, but it's not a number. It's a pointer. It refers to a thing.
A intptr_t
does not. It's an integer value, that is safe to convert to/from a pointer so you can use it for antique APIs, packing it into a pthread
function argument, things like that.
That's why you can do more numbery and bitty things on an intptr_t
than you can on a void*
, and why you should be self-documenting by using the proper type for the job.
Ultimately, almost everything could be an integer (remember, your computer works on numbers!). Pointers could have been integers. But they're not. They're pointers, because they are meant for different use. And, theoretically, they could be something other than numbers.