简体   繁体   English

功能指针与函数调用有什么区别?

[英]What is the difference between Function Pointer vs Function Call?

Hello Friends, 你好朋友,
How can I use an array of function pointers? 我如何使用函数指针数组?
If we will see the above link, it tells us how function pointer works. 如果我们将看到上面的链接,它会告诉我们函数指针是如何工作的。
Now the question is why should I choose function pointer? 现在的问题是我为什么要选择函数指针?
Why can't I use function call directly? 为什么我不能直接使用函数调用?
What are the benifits will I get with function pointer? 我会用函数指针获得什么好处?
eg 例如

enum{a, b, c};
void A();
void B();
void C();
void (*fun[3])() = {A, B, C};

Now when I need to call a function I am doing like,
fun[a](); // This calls function A
// And so on...

Same can be done in function calls also 同样可以在函数调用中完成

like when I need to call function A, B or C. directly I can right like 就像我需要直接调用函数A,B或C.我可以这样

A();
B();
or 
C();

Then why function pointer ? 那为什么function pointer

There are many reasons to use a function pointer, in particular for doing things generically in C. 使用函数指针有很多原因,特别是在C中一般做事情。

The main place you'll see them being used are as an argument to a function. 您将看到它们被使用的主要位置是作为函数的参数。 For example with the function bsearch , it uses a comparison function, passed as a function pointer, to compare items and sort the data: 例如,使用函数bsearch ,它使用比较函数作为函数指针传递,以比较项目并对数据进行排序:

void *bsearch(const void *key, const void *base,
                     size_t nmemb, size_t size,
                     int (*compar)(const void *, const void *));

That allows bsearch to be generic and sort any type of data, since only that comparison function has to know the type of the data. 这允许bsearch是通用的并且可以对任何类型的数据进行排序,因为只有该比较函数必须知道数据的类型。


Another one has to do with avoiding multiple checks. 另一个与避免多次检查有关。 ie. 即。

void makePizza(void) { }

void bakeCake(void) { }

iWantPizza = 1;
...
if (iWantPizza)
   makePizza();
else
   bakeCake();
/* want to call the same function again... */
if (iWantPizza)
   makePizza();
else
   bakeCake();

..

/* alternative */
void (*makeFood)(void) = iWantPizza ? makePizza : bakeCake;

makeFood();
/* want to call the same function again... */
makeFood();

For the example that you showed, one more thing can be done. 对于您展示的示例,还可以做一件事。

Lets say there are bunch of function that needs to run for some device operation. 可以说有一些功能需要为某些设备操作运行。 In simple way, you can write all function calls in another master function and call that master function. 以简单的方式,您可以在另一个主函数中编写所有函数调用并调用该主函数。

Another way to do it is, write all function names in a curly bracket and call each by using a function pointer and a loop. 另一种方法是,将所有函数名称写在大括号中,并使用函数指针和循环调用每个函数名称。 That looks smart. 这看起来很聪明。 I'm not sure how that helps you in better way but I saw this in linux kernel code. 我不确定这对你有什么帮助,但我在linux内核代码中看到了这一点。


I agree to all the answers here. 我同意这里的所有答案。 Apart from this I have some of my own judgements to use function pointer. 除此之外,我有一些自己的判断来使用函数指针。

Lets take an example of some complex math calculation (like printing Fibonacci, integration, fourier Xform, etc...). 让我们举一些复杂的数学计算的例子(比如打印Fibonacci,集成,傅立叶Xform等等)。

You have a function FX(which does that complicated math calculation or anything else) that you use many a times in your program. 你有一个在你的程序中多次使用的函数FX(它执行复杂的数学计算或其他任何事情)。 This function is used in many different jobs. 此功能用于许多不同的工作。

After using your program for a few months, you find out that, for some work, you can improve the function and for some, current one is best. 使用你的程序几个月之后,你会发现,对于某些工作,你可以改进功能,对于某些人来说,当前最好。 What you will do? 你会做什么? Write a new function, go and change the function name at all places. 编写一个新函数,去所有地方更改函数名称。

Everytime you find something better, you are gonna do same. 每次你找到更好的东西,你都会这样做。

Instead, use different function pointer for different work. 相反,使用不同的函数指针进行不同的工作。 At initial stage, all pointers can point to one function. 在初始阶段,所有指针都可以指向一个函数。 When you discover a better function for some work, just divert the pointer and you are done. 当您发现某项工作的更好功能时,只需转移指针即可完成。


Take another scenario. 采取另一种方案。 Here, you have a real big code like mobile phone OS. 在这里,你有一个真正的大代码,如手机操作系统。 (not fully open but half compiled). (不是完全开放但是一半编译)。 You need to add bluetooth driver to it for a particular hardware. 您需要为特定硬件添加蓝牙驱动程序。

Now, you can add or you can leave is the option available in OS. 现在,您可以添加或者您可以离开是OS中可用的选项。

You may need to turn on/off bluetooth from many places. 您可能需要从许多地方打开/关闭蓝牙。

So what OS does is, it makes a function pointer that turn bluetooth ON and use it wherever it is needed. 操作系统所做的是,它创建了一个函数指针,可以将蓝牙打开并在需要的地方使用它。 This code is already compiled so you cannot add your code in it. 此代码已编译,因此您无法在其中添加代码。 But what can be done is, you can write function and make that pointer point to your function. 但是可以做的是,你可以编写函数并使指针指向你的函数。

This is what I have already seen under Android OS. 这是我在Android OS下已经看到的。 (not exactly but nearer) (不完全但更接近)

Now the question is why should I choose function pointer? 现在的问题是我为什么要选择函数指针?
What are the benifits will I get with function pointer? 我会用函数指针获得什么好处?

You use function pointers when you need to implement a Asynchronous mechanism. 您需要实现异步机制时使用函数指针。
You need a function be called asynchronously when something happens. 事情发生时,你需要异步调用一个函数。
How will you know which function to call? 你怎么知道要调用哪个函数?
The address of every function is Unique,So you need to use and store the function address. 每个函数的地址都是唯一的,所以你需要使用和存储函数地址。
Where do you store this function address? 你在哪里存储这个功能地址?
A function pointer 一个函数指针

In my experience, function pointers are mainly used to pass a function as a parameter to another function. 根据我的经验,函数指针主要用于将函数作为参数传递给另一个函数。

Looking at your code, they could also be used like with arrays, so you can just loop through the entire array (which could consist of hundreds of function pointers) and it will just execute them all. 看看你的代码,它们也可以像数组一样使用,所以你可以遍历整个数组(可能包含数百个函数指针),它只会执行它们。

What is the difference between Function Pointer vs Function Call? 功能指针与函数调用有什么区别?

It's like the difference between asking the compiler to "tell me the address of the National Gallery (I might want to go there later and I want to be ready to do it)", rather than "take me to the National Gallery right now (but I won't be paying attention to how you get me there so don't expect me to know later on)". 这就像要求编译器“告诉我国家美术馆的地址(我可能想稍后去那里,我想做好准备)”之间的区别,而不是“现在带我去国家美术馆”(但我不会注意你是怎么把我送到那里所以不要指望我后来知道)“。 Crucially, if you ask for the address/pointer you can write it down in some place like "next Sunday afternoon's big trip"... you don't even have to remember that it is the National Gallery you'll be going to - it can be a pleasant surprise when you get there - but you immediately know your Sunday's entertainment's all sorted. 至关重要的是,如果你要求地址/指针,你可以在某个地方写下来,比如“下周日下午的大旅行”......你甚至不必记住它是你要去的国家美术馆 - 当你到达那里时,这可能是一个惊喜 - 但你立即知道你周日的娱乐活动全部排序。

What benefits will I get with function pointer? 使用函数指针可以获得什么好处?

Well, as above, at the time you set the function pointer you need to make a decision about where you'll call later, but then you can forget about all the reasons for making that decision and just know that later destination's all ready for use. 好吧,如上所述,在你设置功能指针的时候,你需要决定你以后打电话的地方,但是你可以忘记做出决定的所有原因,只知道后来的目的地都准备好了。 。 At the time when you're actually doing stuff... "my Sunday routine: sleep in to 10, eat a big breakfast, go back to bed, have a shower, if I've got plenty of money then go on my Sunday afternoon big trip, meet friends for dinner"... the earlier decision just kicks in to get you to the gallery. 当你实际做的事情......“我的星期天例行公事:睡到10点,吃一顿丰盛的早餐,回去睡觉,洗澡,如果我有足够的钱,那就去我星期天下午的大旅行,和朋友一起吃晚饭“......早先的决定只是为了让你去画廊。 Crucially, you can keep using your familiar Sunday schedule and start "pointing" the "next Sunday afternoon's big trip" address/pointer at new places as they catch your eye, even if they didn't exist when your general schedule was formed. 至关重要的是,你可以继续使用你熟悉的星期日时间表并开始“指点”下一个星期天下午的大旅行地址/指针,因为它们引起你​​的注意,即使它们在你的总体时间表形成时不存在。

You see this post-facto flexibility to change the destination dispatched to at one step in an old routine illustrated well by AusCBloke's mention of bsearch . 你可以看到这种事实上的灵活性,可以通过AusCBloke提到的bsearch在旧例程中将调度目标更改为一步。 qsort is another classic example - it knows the big picture logic of efficiently sorting arrays of arbitrary things, but has to be told where to go to compare two of the things you're actually using it for. qsort是另一个经典的例子 - 它知道有效排序任意事物数组的大图逻辑,但必须告诉它去哪里比较你实际使用它的两个东西。

Function Pointers are pointers(like variable pointers) which point to the address of a function. 函数指针是指针(如变量指针),它指向函数的地址。 They actually calling the underlying function when you dereference them like a function call does. 当你像函数调用那样取消引用它们时,它们实际上调用了底层函数。

The main advantage of a function pointer is that you can pass it to another function as a parameter for example ... 函数指针的主要优点是你可以将它作为参数传递给另一个函数 ,例如......

These are good examples, particularly the first in Urvish's above. 这些都是很好的例子,特别是在Urvish上面的第一个例子。 I have wondered the same thing, and I think the answer is purely design. 我想知道同样的事情,我认为答案纯粹是设计。 In my mind, they are the same result, as in you can point to a function and get a+b or you can just call a function regularly and get a+b, and with the examples on SO, they are usually small and trivial for illustration. 在我看来,它们是相同的结果,因为你可以指向一个函数并得到一个+ b,或者你可以定期调用一个函数并得到一个+ b,并且通过SO上的例子,它们通常是小而琐碎的为了说明。 But , if one had a 10k line C program, and you had to change something fifty times because you made a change, you'd probably pick up pretty quickly why you'd want to use function pointers. 但是 ,如果一个人有一个10k的C系列程序,并且你因为你做了一个改变而不得不改变了五十次,那么你可能很快就会选择使用函数指针的原因。

It also makes you appreciate the design of OOP languages and the philosophy behind OOD. 它还使您欣赏OOP语言的设计和OOD背后的哲学。

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

相关问题 **pointer 和 &pointer 作为函数参数有什么区别? - What is the difference between **pointer and &pointer as function parameter? 定义函数类型和函数指针类型有什么区别? - What is the difference between defining a function type and a function pointer type? main / function 中的指针有区别吗 - Is there a difference between pointer in main / function 函数定义中的指针与数组:void fct1(int * p)和void fct1(int p [])之间的区别是什么? - Pointer vs Array in function definition: what is the difference between void fct1(int *p) and void fct1(int p[])? 普通函数调用和signal()系统调用有什么区别? - What is the difference between normal function call and signal() system call? 函数和* function有什么区别? - what the difference between a function and *function? (函数指示符)和{函数指针}之间的区别? - Difference between (function designator) and {function pointer}? 函数指针和函数名之间的区别 - difference between function pointer and function name 带返回类型指针的 function 和 function 指针之间的区别 - Difference between function with returned type pointer and function pointer 传递2d数组函数时单指针和双指针有什么区别? - When passing 2d array to function what is the difference between single pointer and double pointer?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM