C++ – Understanding the Use of intptr_t

c++pointerssigned-integer

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?

Best Answer

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.