I have a function that takes a function pointer and apply it over a list. It’s prototype is as follows:
void applyList(List *, void applyFunc(void *));
Now I want to supply a function that prints the element in the list. Since I’m not modifying the list element, the print function looks like this:
void printNode(const void *nodeData){
Data *dPtr=(Data*)nodeData;
printf("%s", dPtr->str );
}
//Usage
applyList(list, printNode);
However I got an compiler error saying
expected ‘void (*)(void *)’ but argument is of type ‘void (*)(const void *)’
I don’t want to add const to apply‘s prototype, because I might supply some function that modifies the data. Any suggestion on how to deal with this situation?
Unfortunately, in C function pointers are not polymorphic. At all. Attempting to force a cast leads to undefined behavior.
Your only standard-conforming way out is to write a wrapper function:
Note, however, that your const is kind of useless here:
You just casted away the const declaration. Try to keep it on there: