为什么以及如何取消引用函数指针只是“什么都不做”?
这就是我要说的:
#include<stdio.h>
void hello() { printf("hello"); }
int main(void) {
(*****hello)();
}
来自 here 的评论:
function pointers dereference just fine, but the resulting function designator will be immediately converted back to a function pointer
从回答 here :
Dereferencing (in way you think) a function's pointer means: accessing a CODE memory as it would be a DATA memory.
Function pointer isn't suppose to be dereferenced in that way. Instead, it is called.
I would use a name "dereference" side by side with "call". It's OK.
Anyway: C is designed in such a way that both function name identifier as well as variable holding function's pointer mean the same: address to CODE memory. And it allows to jump to that memory by using call () syntax either on an identifier or variable.
究竟函数指针的解引用是如何工作的?
最佳答案
这不是一个完全正确的问题。至少对于 C,正确的问题是
What happens to a function value in an rvalue context?
(右值上下文是指出现在应用作值的名称或其他引用的任何位置,而不是位置 - 基本上是除赋值左侧之外的任何位置。名称本身来自 右侧-作业的手边。)
好的,那么在右值上下文中函数值会发生什么?它立即隐式转换为指向原始函数值的指针。如果您使用 *
取消引用该指针,您将再次获得相同的函数值,该值会立即隐式转换为指针。您可以根据需要多次执行此操作。
您可以尝试两个类似的实验:
如果在 lvalue 上下文(赋值的左侧)中取消引用函数指针会发生什么。 (答案将取决于您的期望,如果您记住函数是不可变的。)
在左值上下文中,数组值也被转换为指针,但它被转换为指向 element 类型的指针,而不是指向数组的指针。因此,取消引用它会给你一个元素,而不是一个数组,并且你表现出的疯狂不会发生。
希望这会有所帮助。
附:至于为什么函数值会被隐式转换为指针,答案是对于我们这些使用函数指针的人来说,不用&
是非常方便的无处不在。还有双重便利:调用位置的函数指针会自动转换为函数值,因此您不必编写 *
即可通过函数指针进行调用。
附言与 C 函数不同,C++ 函数可以重载,我没有资格评论语义在 C++ 中的工作原理。
关于c++ - 函数指针的解引用是如何发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2795575/