Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function argument of a function in the function implementation?

If I have a declaration like this:

int foo1 (int foo2 (int a));

How can I implement this foo1 function? Like,

int foo1 (int foo2 (int a))
{
    // How can I use foo2 here, which is the argument?
}

And how do I call the foo1 function in main? Like:

foo1(/* ??? */);
like image 528
javac Avatar asked Sep 09 '26 22:09

javac


1 Answers

When you declare a function parameter as a function, the compiler automatically adjusts its type to "pointer to function".

int foo1 (int foo2 (int a))

is exactly the same as

int foo1 (int (*foo2)(int a))

(This is similar to how declaring a function parameter as an array (e.g. int foo2[123]) automatically makes it a pointer instead (e.g. int *foo2).)

As for how you can use foo2: You can call it (e.g. foo2(42)) or you can dereference it (*foo2), which (as usual with functions) immediately decays back to a pointer again (which you can then call (e.g. (*foo2)(42)) or dereference again (**foo2), which immediately decays back to a pointer, which ...).

To call foo1, you need to pass it a function pointer. If you don't have an existing function pointer around, you can define a new function (outside of main), such as:

int bar(int x) {
    printf("hello from bar, called with %d\n", x);
    return 2 * x;
}

Then you can do

foo1(&bar);  // pass a pointer to bar to foo1

or equivalently

foo1(bar);  // functions automatically decay to pointers anyway
like image 160
melpomene Avatar answered Sep 11 '26 17:09

melpomene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!