Question about function arguments...

Feb 23, 2011 at 5:29am
I have a question about function arguments:

Is it possible to send a particular function to another function as an argument?

Also, is it possible to store a particular function as a variable in such a way so that you can execute it?

There has to be some back way or trick to do this, but I'm baffled.
Feb 23, 2011 at 5:34am
For your second question, do you mean something like this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int someFunction();

int main(int argc, char* argv[])
{
    int x = someFunction();

    return 0;
}

int someFunction()
{
    return 5+2;
}


You can certainly do that.
Feb 23, 2011 at 5:59am
appnerd means

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int mul( int a, int b )
    { return a * b; }


int do_it( int (*func)( int, int ), int a, int b )
{
    return func( a, b );
}

int main()
{
    int (*function)( int, int ) = mul;
    do_it( function, 42, 3 );
}


Hints:

int (*function)( int, int ) = mul; declares a variable named 'function' which is of type "pointer to function accepting two ints as parameters and returns int" and assigns it the address of the function 'mul'.


Topic archived. No new replies allowed.