javac
javac

Reputation: 461

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(/* ??? */);

Upvotes: 3

Views: 135

Answers (3)

Mazhar
Mazhar

Reputation: 575

Have a look at the following code, it shows how to call functions they way you wanted to call.

 #include <stdio.h>


/* Declaration of foo1 . It receives a specific function pointer foo2 and an integer. */
int foo1 (int (*foo2)(int), int a);

int cube(int number)
{
    return (number * number * number);
}

int square(int number)
{
    return (number * number);
}

int foo1 (int (*foo2)(int), int a)
{
    int ret;

    /* Call the foo2 function here. */
    ret = foo2(a);

    printf("Result is: %d\r\n", ret);

    return (ret);
}

int main()
{
    int a = 3;

    foo1(square, a);
    foo1(cube, a);

    return 0;
}

Upvotes: -1

Stef1611
Stef1611

Reputation: 2399

Perhaps, this simple example could help you :

#include <stdio.h>

int foo1 (int foo2 (int),int i);
int sub_one (int);
int add_one (int);

int main() {
    int i=10,j;
    j=foo1(sub_one,i);
    printf("%d\n",j);
    j=foo1(add_one,i);
    printf("%d\n",j);
}

int sub_one (int i) {
    return i-1;
}
int add_one (int i) {
    return i+1;
}

int foo1 (int foo2 (int),int i) {
    return foo2(i);
}

Upvotes: 0

melpomene
melpomene

Reputation: 85877

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

Upvotes: 8

Related Questions