为什么以及如何取消对函数指针的引用只是“什么都不做”?
这就是我要说的:
#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?
(右值上下文是名称或其他引用出现在它应该用作值的任何位置,而不是位置 - 基本上任何地方,除了赋值的左侧。名称本身来自 右侧 - 作业的手边。)
好的,那么右值上下文中的函数值会发生什么?它立即隐式转换为指向原始函数值的指针。如果您使用 *
取消引用该指针,您将再次获得相同的函数值,该值会立即隐式转换为指针。您可以多次执行此操作。
您可以尝试两个类似的实验:
如果您在左值 上下文(赋值的左侧)中取消引用函数指针,会发生什么情况。 (如果您牢记函数是不可变的,答案将是您所期望的。)
数组值也被转换为左值上下文中的指针,但它被转换为指向元素 类型的指针,而不是指向数组的指针。因此,取消引用它会给你一个元素,而不是一个数组,并且你表现出的疯狂不会发生。
希望这对您有所帮助。
附言至于为什么函数值被隐式转换为指针,答案是对于我们这些使用函数指针的人来说,不必使用&
是一个很大的方便无处不在。还有一个双重便利:调用位置的函数指针会自动转换为函数值,因此您无需编写 *
即可通过函数指针进行调用。
附言与 C 函数不同,C++ 函数可以重载,我没有资格评论 C++ 中的语义如何工作。
关于c++ - 函数指针的取消引用是如何发生的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43158146/