c赋值运算符=
任何人都可以。请解释以下c程序的工作原理: 具体如何将函数'fun'分配给(*p)() = fun
;我需要知道编译器如何编译这段代码。c赋值运算符=
#include<stdio.h>
int fun(); /* function prototype */
int main()
{
int (*p)() = fun;
(*p)();
return 0;
}
int fun()
{
printf("Hello World\n");
return 0;
}
每个函数都存在于某个地方的内存中。声明:
int (*p)() = fun;
将函数fun的存储位置分配给p。然后行:
(*p)();
正在调用存在于p指向的内存位置的函数。
Interweb充满了“函数指针”的信息。
谢谢。这解决了我的问题 – abhey
如果你看看通过gcc
(与-O0
)生成的代码:
movl $_fun, -4(%ebp)
movl -4(%ebp), %eax
call *%eax
它存储fun
函数的地址在堆栈变量,然后简单地间接调用这个地址。
这是最快的电话吗?比f()更快; ? –
@tuğrulbüyükışık当然不是,并启用优化'gcc'直接发出'调用_fun'这个程序。 – ouah
查找“函数指针”。 – Mysticial