Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can change the pointer's function?

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;
}
like image 252
macabeus Avatar asked Sep 01 '26 04:09

macabeus


1 Answers

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.

like image 103
Persixty Avatar answered Sep 03 '26 18:09

Persixty