问题
Suppose there is a pointer f
declared to some function say int foo(int)
as :
int (*f)(int)=foo;
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)
and
y=f(x)
are same in C and calls function foo()
....(x and y are of int type).
For arrays I know that if p is pointer to any array a.
p[i]=*(p+i)=*(&a[0]+i)=*(a+i)=a[i]
.
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" ?
回答1:
Pre-ANSI C used to required that you dereference function pointers before calling them.
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).
来源:https://stackoverflow.com/questions/54962296/logic-behind-calling-function-by-using-pointer-to-a-function