c++ - What is the use of intptr_t

c++ – What is the use of intptr_t?

c++ – What is the use of 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, §,

These types are optional.

Theres 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 its not a number. Its a pointer. It refers to a thing.

A intptr_t does not. Its 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.

Thats 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 theyre not. Theyre pointers, because they are meant for different use. And, theoretically, they could be something other than numbers.

c++ – What is the use of intptr_t?

The uintptr_t type is very useful when writing memory management code. That kind of code wants to talk to its clients in terms of generic pointers (void *), but internally do all kinds of arithmetic on addresses.

You can do some of the same things by operating in terms of char *, but not everything, and the result looks like pre-Ansi C.

Not all memory management code uses uintptr_t – as an example, the BSD kernel code defines a vm_offset_t with similar properties. But if you are writing e.g. a debug malloc package, why invent your own type?

Its also helpful when you have %p available in your printf, and are writing code that needs to print pointer sized integral variables in hex on a variety of architectures.

I find intptr_t rather less useful, except possibly as a way station when casting, to avoid the dread warning about changing signedness and integer size in the same cast. (Writing portable code that passes -Wall -Werror on all relevant architectures can be a bit of a struggle.)

Related posts on c++   :

Leave a Reply

Your email address will not be published.