What is guaranteed about the size of a function pointer?

前端 未结 4 526
梦谈多话
梦谈多话 2020-11-27 06:15

In C, I need to know the size of a struct, which has function pointers in it. Can I be guaranteed that on all platforms and architectures:

  • the size of a void*
4条回答
  •  无人及你
    2020-11-27 07:08

    No, no, no.

    C doesn't favour Harvard architectures with different code and data pointer sizes, because ideally when programming for such an architecture you want to store data in program memory (string literals and the like), and to do that you'd need object pointers into the code space. But it doesn't forbid them, so as far as the standard is concerned function pointers can refer to an address space which has a different size from the data address space.

    However, any function pointer can be cast to another function pointer type[*] and back without trashing the value, in the same way that any object pointer can be cast to void* and back. So it would be rather surprising for function pointers to vary in size according to their signature. There's no obvious "use" for the extra space, if you have to be able to somehow store the same value in less space and then retrieve it when cast back.

    [*] Thanks, schot.

提交回复
热议问题