Pascal Cuoq
Pascal Cuoq

Reputation: 80276

Is there a recommended integer type to store function pointers in standard C

The C99 standard has uintptr_t, a recommended integer type to convert data pointers (pointers to objects) to, but I did not find an equivalent integer type to store function pointers. Did I overlook it?

A specific compiler could define such a type even though it is not in the standard, but a compiler is more likely to state that a function pointer can be stored in (say) a uint64_t than to define a new type.

Another difference is that it can make sense to do integer arithmetic on a data pointer in ways that it doesn't on function pointer. One common idiom is (int*)(((uintptr_t)p + 15) & ~(uintptr_t)15) but there is no reason to apply this idiom to a function pointer.

Upvotes: 4

Views: 263

Answers (3)

Yu Hao
Yu Hao

Reputation: 122383

There's no such integer type for function pointers to convert.

One of the reasons is: on some machines, function addresses can be very large, bigger than any data pointers.

Upvotes: 3

user529758
user529758

Reputation:

I did not find an equivalent integer type to store function pointers

That's because you can't convert function pointers to integers. Doing so results in undefined behavior.

Upvotes: 3

Jens Gustedt
Jens Gustedt

Reputation: 78903

No there is no such recommended pointer type.

To store the pointer you may use any other function pointer type, as long as you don't call your function through it.

If you convert your pointer than back to the original type you may call your function. This is always guaranteed to work.

Upvotes: 3

Related Questions