function pointer

02 Feb 2011

Hi, I have declared a function pointer

typedef void (*fpTasks)(char *taskName);

and then I use an array as in

fpTasks tasks[]  = {execute(task1),execute(task2),execute(task3),execute(task4)}; 

The execute function has the same form

void execute(char *task);

where each task1,task2 is a char array. The thing is I am getting an error where it declares that a value of type void cannot be used to initialize an entity of type fpTasks. What i find confusing is that the fpTasks function pointer is of type void. Any idea how can I fix this. Thanks.

02 Feb 2011

An expression execute or &execute will have a type matching fpTasks (a function pointer). However, execute(task1) is a function call, and thus has the type of void (return value of the function). In short, you can't initialize a pointer table this way. I think what you should do is put tasks themselves into an array, and then call execute(tasks[i]) in a loop. If that's not it, explain more about what you want to achieve.

02 Feb 2011

Thank you, but I already tried that and it works as you said , but in this case I want to pass an argument to the function in the array. Since the function does the same thing (It print the properties of each task), I figured that I just have to pass the name of the task to each instance of a function-pointer inside the task.

Otherwise I will have to go with the old route and write four functions, one for each task.

So my question is : Is there a way to pass an argument to a function inside an array of function pointers ?

On the main file I am using a switch construct to select the appropriate function that should be executed based on the value of an index.

02 Feb 2011

What you want is called closures, and C does not support them (there is a proposal for C++ however). You could make small wrapper functions that would call execute() with a specific task and put those wrappers into an array, though I don't really see an advantage of such approach.

02 Feb 2011

Never head of them , I'll do a bit of reading but I think I'll go back to the old way. Thanks for clarifying this.

D