Don*_*uck 2 javascript c function
我想知道 C 语言(对于函数void)是否有与此 javascript 代码等效的代码:
var myFunction;
myFunction = function(){
//Some code
}
Run Code Online (Sandbox Code Playgroud)
并不真正等效(因为 C 是一种静态语言,不支持匿名或嵌套函数),但您可以拥有一个作为函数指针的变量,并使其指向与该变量类型匹配的不同编译函数。
非常简单和基本的例子:
#include <stdio.h>
void function1(void)
{
printf("function1\n");
}
void function2(void)
{
printf("function2\n");
}
int main(void)
{
// Declare a variable that is a pointer to a function taking no arguments
// and returning nothing
void (*ptr_to_fun)(void);
ptr_to_fun = &function2;
ptr_to_fun();
ptr_to_fun = &function1;
ptr_to_fun();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的程序会打印出
功能2 功能1