Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}

.

like image 624
user2839891 Avatar asked Feb 27 '15 21:02

user2839891


4 Answers

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.

like image 134
haccks Avatar answered Oct 25 '22 21:10

haccks


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)
like image 27
AnT Avatar answered Oct 25 '22 23:10

AnT


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
like image 21
user253751 Avatar answered Oct 25 '22 22:10

user253751


According to cdecl, foo is:

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

like image 41
imreal Avatar answered Oct 25 '22 23:10

imreal