Where exactly do function pointers point?

后端 未结 5 2011
栀梦
栀梦 2021-02-13 04:41

Given that all the primitive data types and objects have memory allocated, it is intuitively easy to imagine the pointers to these types.

But where exactly do function p

5条回答
  •  渐次进展
    2021-02-13 05:23

    A function pointer contains the address of a function -- whatever that means for a given system. You can use it to call the function indirectly, you can assign and compare function pointer values. You can also convert a function pointer to another pointer-to-function type, and so forth.

    The most straightforward way for a compiler to implement a function pointer is as the memory address of the function, and most compilers do it that way, but the language standard doesn't specify that. Some systems (I think IBM's AS/400 is an example) store additional information in function pointers. A compiler could implement function pointers as integer indices into a table of descriptors, as long as the required semantics are implemented properly.

    It's not possible to dereference a function pointer. A function call requires a pointer, not a function name, as its prefix expression; if you use a function name, that name is implicitly converted to a pointer (as far as the language is concerned; the generated machine code might be different). So there's no portable way for a program to detect whether function pointers actually contain memory addresses or not.

    Non-portably, given a function func, you can do something like:

    printf("Address of func is %p\n", (void*)func);
    

    and you'll probably see something that looks like a human-readable representation of a memory address. But strictly speaking, the behavior of the conversion of the function pointer to void* is not defined by the language, and it might not work on some systems.

    You might even be able to convert a function pointer to unsigned char* and examine the function's machine code, but goes far beyond anything defined by the C standard.

    It's best to treat function pointers as opaque values that refer to particular functions in some unspecified manner.

提交回复
热议问题