What is the point of function pointers?

2020-01-22 13:09发布

I have trouble seeing the utility of function pointers. I guess it may be useful in some cases (they exist, after all), but I can't think of a case where it's better or unavoidable to use a function pointer.

Could you give some example of good use of function pointers (in C or C++)?

16条回答
何必那么认真
2楼-- · 2020-01-22 13:49

I use function pointers extensively, for emulating microprocessors that have 1-byte opcodes. An array of 256 function pointers is the natural way to implement this.

查看更多
▲ chillily
3楼-- · 2020-01-22 13:53

The "classic" example for the usefulness of function pointers is the C library qsort() function, which implements a Quick Sort. In order to be universal for any and all data structures the user may come up with, it takes a couple of void pointers to sortable data and a pointer to a function that knows how to compare two elements of these data structures. This allows us to create our function of choice for the job, and in fact even allows for choosing the comparison function at run time, e.g. for sorting ascending or descending.

查看更多
劳资没心,怎么记你
4楼-- · 2020-01-22 13:53

One use of function pointer could be where we may not want to modify the code where the function is getting called (meaning thereby the call might be conditional and under different conditions, we need to do different sort of processing). Here the function pointers are very handy, since we do not need to modify the code at the the place where the function is getting called. We simply call the function using the function pointer with appropriate arguments. The function pointer can be made to point to different functions conditionally. (This can be done somewhere during initialization phase). Moreover the above model is very helpful, if we are not in position to modify the code where it is getting called (suppose it's a library API we can't modify). The API uses a function pointer for calling the appropriate user defined function.

查看更多
Summer. ? 凉城
5楼-- · 2020-01-22 13:55

Examples:

  1. Custom sorting/searches
  2. Different patterns (like Strategy, Observer)
  3. Callbacks
查看更多
登录 后发表回答