简体   繁体   English

在C中使用函数指针

[英]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. 这个概念在OOP语言中非常重要,可以使用函数指针创建。

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. 例如,C库具有qsort()函数。 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. 因此,当qsort()本身被编写时,它(或编写它的程序员)不知道它将被要求排序的对象类型。 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. 此外,可能会要求qsort()在一次调用中对int进行排序,并在之后立即对struct foo对象进行排序。 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. 传递函数指针允许以这样的方式编写qsort() ,使得它不需要了解被排序的项目。 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. 正如Justin上面正确指出的那样,它用于模拟多态性和回调。

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 . 就像,当你可以写一个常量42时,使用变量int x有什么好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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