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);
}
.
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.
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)
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
According to cdecl, foo
is:
declare foo as function (int) returning pointer to function (int) returning int
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With