Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of uintptr_t/intptr_t for pointers to functions?

Afaik uintptr_t and intptr_t can be used to hold any pointer to void. Hence these types can be used to store pointers to data.

In C99 or later, are there similar signed and unsigned integer types capable of holding pointers to functions?

like image 788
jotik Avatar asked Apr 04 '16 13:04

jotik


People also ask

Is Uintptr_t a pointer?

uintptr_t is an unsigned integer type that is capable of storing a data pointer (whether it can hold a function pointer is unspecified). Which typically means that it's the same size as a pointer. It is optionally defined in C++11 and later standards.

Can Size_t hold a pointer?

size_t type It is the type of the result returned by sizeof operator. The type's size is chosen so that it can store the maximum size of a theoretically possible array of any type. On a 32-bit system size_t will take 32 bits, on a 64-bit one 64 bits. In other words, a variable of size_t type can safely store a pointer.

Can you cast function pointers?

We can cast a function pointer to another function pointer type but cannot call a function using casted pointer if the function pointer is not compatible with the function to be called. If a function pointer is casted to a function pointer of a different type and called, it results into undefined behaviour.

What is intptr_t type?

intptr_t is a signed integer memsize-type that can safely store a pointer regardless of the platform capacity. The type intptr_t is similar to the types ptrdiff_t and INT_PTR. The size of the type depends upon the data model.


1 Answers

No, there are no such types.

Function pointers may only be reliably cast to other function pointer types (and then, only dereferenced while pointing to the correct function type).

The conversion of function pointers to integers in C is covered by 6.3.2.3/6:

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

Note that even if the integer type is large enough, casting to integer and back to function pointer is not guaranteed to retrieve the original function pointer.

In C++, the text is in [expr.reinterpret.cast] points 4 and 6. The behaviour is similar, but it explicitly guarantees that if an integer of sufficient size exists, then converting function pointer to integer and back again does retrieve the original function pointer.

like image 89
M.M Avatar answered Sep 28 '22 16:09

M.M