Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using function as parameter

Tags:

c++

Possible Duplicate:
How do you pass a function as a parameter in C?

Suppose I have a function called

void funct2(int a) {  }   void funct(int a, (void)(*funct2)(int a)) {   ;   } 

what is the proper way to call this function? What do I need to setup to get it to work?

like image 553
Mark Avatar asked Jun 14 '11 06:06

Mark


People also ask

Can I pass a function as a parameter in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer.

Can a function be a parameter?

A function can take parameters which are just values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself.

What is function parameter in C language?

Parameters and Arguments Information can be passed to functions as a parameter. Parameters act as variables inside the function. Parameters are specified after the function name, inside the parentheses.

Can we pass function as parameter?

Because functions are objects we can pass them as arguments to other functions. Functions that can accept other functions as arguments are also called higher-order functions. In the example below, a function greet is created which takes a function as an argument.


1 Answers

Normally, for readability's sake, you use a typedef to define the custom type like so:

typedef void (* vFunctionCall)(int args); 

when defining this typedef you want the returning argument type for the function prototypes you'll be pointing to, to lead the typedef identifier (in this case the void type) and the prototype arguments to follow it (in this case "int args").

When using this typedef as an argument for another function, you would define your function like so (this typedef can be used almost exactly like any other object type):

void funct(int a, vFunctionCall funct2) { ... } 

and then used like a normal function, like so:

funct2(a); 

So an entire code example would look like this:

typedef void (* vFunctionCall)(int args);  void funct(int a, vFunctionCall funct2) {    funct2(a); }  void otherFunct(int a) {    printf("%i", a); }  int main() {    funct(2, (vFunctionCall)otherFunct);    return 0; } 

and would print out:

2 
like image 106
Matt Razza Avatar answered Oct 04 '22 11:10

Matt Razza