About Pointers To Functions in function declarations

我是研究僧i 提交于 2019-11-27 09:01:44
Nawaz

When you write int fun2(int fun()), the parameter int fun() converts into int (*fun)(), it becomes exactly equivalent to this:

int fun2(int (*fun)());

A more famiiar conversion happens in case of array when you declare it as function parameter. For example, if you've this:

int f(int a[100]);

Even here the parameter type converts into int*, and it becomes this:

int f(int *a);

The reason why function type and array type converts into function pointer type, and pointer type, respectively, is because the Standard doesn't allow function and array to be passed to a function, neither can you return function and array from a function. In both cases, they decay into their pointer version.

The C++03 Standard says in §13.1/3 (and it is same in C++11 also),

Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).

And a more interesting discussion is here:

asaelr

int fun2(int (*fun)()) and int fun2(int fun()) are exactly the same. When you declare a function argument from a function type, the compiler uses it as if it were a pointer to the same function type.

These two function definitions are equivalent in C:

 int fun2(int fun()) { ... }

and

 int fun2(int (*fun)()) { ... }

In the first function the parameter is adjusted to a function pointer. See C Standard paragraph:

(C99, 6.7.5.3p8) "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1."

Looking to it in a lower level (and in a x86-based architecture):

int fun2(int fun())

int fun()'s address is pushed into the stack and passed to fun2() function.

int fun2(int (*fun)())

int fun()'s pointer address is pushed into the stack and passed to fun2() function.

The result is the same, except that with second one, you pass the fun()'s address by reference, and in the first one you pass it by value.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!