简体   繁体   中英

How to use the pointer of a function in C? (No C++)

As the title says, how do I use the pointer of a function in C? Can I just take the address of the function name and pass it to another function; then dereference it and call it?

Thanks a lot.

If you know the function address, then yes. For example:

int add(int a, int b)
{
    return a + b;
}

int sub(int a, int b)
{
    return a - b;
}

int operation(int (*op)(int, int), int a, int b)
{
    return op(a, b);
}

Then just call it like this:

printf("%d\n", operation(&add, 5, 3)); // 8
printf("%d\n", operation(&sub, 5, 3)); // 2

You can even do some array tricks:

int op = 0;
int (*my_pointer[2])(int, int) =
{
    add, // op = 0 for add
    sub  // op = 1 for sub
};
printf("%d\n", my_pointer[op](8, 2)); // 10

well to answer your question precisely, there is a provision in C for such needs which is called " function pointer ".

But you have to follow certain rules,

1) All the functions you want to call using function pointer must have same return type. 2) All the functions you want to call using function pointer must have same no of arguments and argument types.

For example,

int add(int, int); int sub(int, int);

for above two functions you can write function pointer as,

int (*operation)(int , int);

and you can use it just as described by Flavio Torbio .

hope it helps.....

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