Reputation: 1487
What standard-defined integer type should I use for holding pointer to functions? Is there a (void*)
-like type for functions that can hold any functions?
It's very certain that it's not [u]intptr_t
because the standard said explicitly it's for pointers to objects and the standard makes a clear distinction between pointer to objects and pointer to functions.
Upvotes: 3
Views: 216
Reputation: 1487
It's very certain that it's not
[u]intptr_t
It's true. But the distinction is only made to guarantee the correctness of some essential conversions. If you look at the 2nd edition of "The C Programming Language", then the distinction is more subtle to notice than the current wording in the standard.
If you target platforms with operating systems, then [u]intptr_t
is probably exactly what you want, as:
POSIX specifies dlsym
function that returns void *
with the requirement that result can be casted to function pointers and be usable.
Win32 GetProcAddress
is defined in such way that, if the return values' not NULL, it'll be a valid memory address that's valid for functions and/or objects.
Upvotes: 2
Reputation: 153447
There is no specified type for an integer type that is sufficient to encode a function pointer.
Alternatives:
Change code to negate the need for that integer type. Rarely is such an integer type truly needed.
Use an array: unsigned char[sizeof( int (*)(int)) )]
and int (*f)(int))
within union
to allow some examination of the integer-ness of the pointer. Still there may be padding issues. Comes down to what code want to do with such an integer.
Use uintmax_t
and hope it is sufficient. A _Static_assert(sizeof (uintmax_t) >= sizeof (int (*)(int)) );
is a reasonable precaution though not a guarantee of success.
The limiting spec
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. C17dr § 6.3.2.3 6
Note even [u]intptr_t
for object pointer types are a guarantee either as they are optional types.
Upvotes: 3