[英]I can change the pointer's function?
In script languages, such as Perl and Python, I can change function in run-time. 在脚本语言中,例如Perl和Python,我可以在运行时更改函数。 I can do something in C by changing the pointer to a function?
我可以通过将指针更改为函数来在C中执行某些操作吗?
Something like: 就像是:
void fun1() {
printf("fun1\n");
}
void fun2() {
printf("fun2\n");
}
int main() {
fun1 = &fun2;
fun1(); // print "fun2"
return 0;
}
Yes; 是; You can and this is the simple program which will help you in understanding this
你可以,这是一个简单的程序,可以帮助你理解这一点
#include <stdio.h>
void fun1() {
printf("fun1\n");
}
void fun2() {
printf("fun2\n");
}
int main() {
void (*fun)() = &fun1;
fun(); // print "fun1"
fun = &fun2;
fun(); // print "fun2"
return 0;
}
➤ ./a.exe
fun1
fun2
You can't change fun1, but you can declare a function pointer (not a function, only a pointer to a function). 你不能改变fun1,但你可以声明一个函数指针(不是函数,只是指向函数的指针)。
void (*fun)();
fun = fun1;
fun(); /* calls fun1 */
fun = fun2;
fun(); /* calls fun2 */
As you might have noticed it is not necessary to take the address of fun1/fun2 explicitely, you can omit the address-of operator '&'. 您可能已经注意到没有必要明确地获取fun1 / fun2的地址,您可以省略运算符'&'的地址。
No. You can't do that . 不,你不能这样做。
You can regard fun1 as a placeholder for the fixed entry point of that function. 您可以将fun1视为该函数的固定入口点的占位符。
The semantic you are looking for is that from fun1=&fun2;
你正在寻找的语义来自
fun1=&fun2;
point on every call to fun1
causes fun2
to be called. 指向
fun1
每次调用都会导致调用fun2
。
fun1
is a value not a variable. fun1
是一个值而不是一个变量。 In the same way in the statement int x=1;
在语句
int x=1;
以相同的方式int x=1;
x
is a variable and 1
is a value. x
是变量, 1
是值。
Your code makes no more sense than thinking 1=2;
你的代码没有比思考
1=2;
更有意义了1=2;
will compile and from that point on x=x+1;
将编译并从那一点开始
x=x+1;
will result in x
being incremented by 2. 将导致
x
增加2。
Just because fun1
is an identifier doesn't mean it's a variable let alone assignable. 仅仅因为
fun1
是一个标识符并不意味着它是一个变量,更不用说可分配了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.