What does this weird function pointer declaration in C mean? [duplicate]

元气小坏坏 提交于 2019-12-06 18:03:15

问题


Can anyone please explain what int ((*foo(int)))(int) in this does?

int (*fooptr)(int);
int ((*foo(int)))(int); // Can't understand what this does.

int main()
{
    fooptr = foo(0);
    fooptr(10);
}

.


回答1:


int ((*foo(int)))(int);

This declares foo as a function that expects an int type argument and returns a pointer to a function that expects an int type argument and return an int.

To be more clear:

          foo                           -- foo
        foo(   )                        -- is a function
        foo(int)                         --  taking an int argument
       *foo(int)                          --   returning a pointer
     (*foo(int))(  )                       --   to a function that
    (*foo(int))(int)                        --     takes an int argument
   int (*foo(int))(int)                      --     and returning an int   

Here is a good explanation for the same.




回答2:


foo

is what we declare.

foo(int)

It is a function that takes a single int argument

*foo(int)

and returns a pointer

((*foo(int)))(int)

to a function that takes a single int argument

int ((*foo(int)))(int)

and returns an int.

One pair of () is redundant. The same thing can be expressed as

int (*foo(int))(int)



回答3:


There already answers to this, but I wanted to approach it in the opposite way.

A function declaration looks the same as a variable declaration, except that the variable name is replaced by the function name and parameters.

So this declares bar as a pointer to a function that takes an int and returns an int:

int (*bar)(int);

If, instead of a variable bar, it's a function foo(int) with that return value, you replace bar with foo(int) and get:

int (*foo(int))(int);
//    ^^^^^^^^
// this was "bar" before

Add an unnecessary pair of parentheses and you get:

int ((*foo(int)))(int);
//   ^         ^
//  extra parentheses



回答4:


According to cdecl, foo is:

declare foo as function (int) returning pointer to function (int) returning int



来源:https://stackoverflow.com/questions/28775057/what-does-this-weird-function-pointer-declaration-in-c-mean

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