简体   繁体   中英

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;
}

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; 
 }

Output

➤ ./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).

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 '&'.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM