简体   繁体   中英

Use of function pointer in C

当我们只需调用该函数就可以使用该函数时,将函数作为参数传递给另一个函数有什么好处。

It's one way to simulate polymorphism and/or callbacks.

A program or client may benefit from client entry points in some contexts. This is a common way to achieve that. It can be used improve modularity or improve physical separation of multiple implementations.

Using function pointers you can create dynamic dispatch behavior. The dynamic "type", and not the static "type" will "determine" which function will be invoked.

This concept is very important in OOP languages, and can be created using function pointers.

Because when the function that takes the function pointer is written, it's not necessarily known what function it should call (I hope that makes some sense). Also, the function might be asked to use different function pointers to do different things.

for example, the C library has the qsort() function. It takes a function pointer to perform the comparison of the objects being sorted. So, when qsort() itself is written, it (or the programmer writing it) have no idea what kinds of objects it's going to be asked to sort. So a function pointer is used to provide that capability.

Also, qsort() may be asked to sort int s in one call, and struct foo objects immediately after. Passing a function pointer allows qsort() to be written in such way that it doesn't need to know much about the items being sorted. That information (the size of the objects being sorted and how to compare them) can be passed to it as parameters.

As correctly pointed out by Justin above, it is used for simualting Polymorphism and callbacks.

You can refer to this link to get details on function pointers and how to use them.

If you don't know in advance (at compile time) which function you're going to use, then it's useful that you can put a (pointer to the) function into a variable.

It's like, what's the advantage of using a variable int x when you could just write a constant 42 .

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