通过使用“指向函数的指针"来调用函数背后的逻辑. [英] Logic behind calling function by using "Pointer to a function"

查看:63
本文介绍了通过使用“指向函数的指针"来调用函数背后的逻辑.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个指向某个函数的指针 f 声明为 int foo(int) as:

Suppose there is a pointer f declared to some function say int foo(int) as :

int (*f)(int)=foo;

虽然提到要使用此ponter调用 foo()函数,该ponter作为参数传递给其他函数.我碰到一个声明,说

While mentioning about calling foo() function by using this ponter which is passed as argument to some other function. I have come across a statement saying that both

y =(* f)(x)

y = f(x)

在C语言中相同,并调用函数 foo()....(x和y为int类型).

are same in C and calls function foo()....(x and y are of int type).

对于数组,我知道如果p是指向任何数组a的指针.

For arrays I know that if p is pointer to any array a.

p [i] = *(p + i)= *(& a [0] + i)= *(a + i)= a [i] .

所以写 p [i] *(p + i)是同一回事.但是我不会得到指针功能"案例的逻辑. y =(* f)(x) y = f(x)如何相同?有没有什么公式可以理解这一点,就像在指向数组的指针"的情况下一样?

So writing p[i] and *(p+i) are same thing. But I won't get the logic for "pointer to function" case. How y=(*f)(x) and y=f(x) are same? Is there any formula to understand this as it is there in case of "pointer to arrays" ?

推荐答案

ANSI C以前要求在调用函数指针之前先取消引用它们.

Pre-ANSI C used to required that you dereference function pointers before calling them.

当C变得标准化时,人们发现除了调用它以外,您不能用函数指针做很多事情(指针算术对函数指针没有意义-函数指针指向汇编指令块的长度)其中取决于具体的函数,而不取决于函数的类型.这也是您无法拥有函数数组的原因),因此 f(x)等效于(* f)(x)(甚至是(**** f)(x)(**& ** f)(x)等)其他组合),只要 f 是函数指针或单间接函数指针(如果它是指向函数指针的指针,则至少需要一个 * ,因此表示乘法间接指针).

When C was getting standardized, people figured out there wasn't much you could do with a function pointer except call it (pointer arithmetic doesn't make sense on function pointers -- function pointers point to blocks of assembly instructions the length of which depends on the concrete function, not on the functions type. That is also the reason you can't have arrays of functions) so f(x) was made equivalent to (*f)(x) (or even (****f)(x) or (**&**f)(x) and various other combinations) as long as f is either a function or a singly-indirect function pointers (if it's a pointer to a function pointer, you need at least one * and so on for multiply indirect pointers).

这篇关于通过使用“指向函数的指针"来调用函数背后的逻辑.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆