Reputation: 4582
In script languages, such as Perl and Python, I can change function in run-time. I can do something in C by changing the pointer to a function?
Something like:
void fun1() {
printf("fun1\n");
}
void fun2() {
printf("fun2\n");
}
int main() {
fun1 = &fun2;
fun1(); // print "fun2"
return 0;
}
Upvotes: 2
Views: 123
Reputation: 8589
No. You can't do that.
You can regard fun1 as a placeholder for the fixed entry point of that function.
The semantic you are looking for is that from fun1=&fun2;
point on every call to fun1
causes fun2
to be called.
fun1
is a value not a variable. In the same way in the statement int x=1;
x
is a variable and 1
is a value.
Your code makes no more sense than thinking 1=2;
will compile and from that point on x=x+1;
will result in x
being incremented by 2.
Just because fun1
is an identifier doesn't mean it's a variable let alone assignable.
Upvotes: 6
Reputation: 16726
You can't change fun1, but you can declare a function pointer (not a function, only a pointer to a function).
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 '&'.
Upvotes: 6
Reputation: 4880
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
Upvotes: 6