Casting Arguments in Function Pointers,
Members - Reputation: 305
Posted 05 December 2012 - 04:52 AM
I have a question about function pointer argument casting in C.
Is it ok to cast any arguments to void*, or only to cast all pointer types to void*. For example, while I'm fairly certain that (1) is correct, is (2) also correct?
(1) int numcmp(char * s1, char * s1);
qsort(..., (int (*)(void*, void*)) (numcmp));
(2) int numcmp(int i1, int i2);
qsort(..., (int(*)(void*, void*))(numcmp));
Also, are there any other types safe to cast the arguments to when passing around function pointers, i.e. other than void*.
Thanks for the help.
I wonder as I wander...
Moderators - Reputation: 9972
Posted 05 December 2012 - 05:27 AM
But 2 wouldn't even work as you expect anyway, because qsort passes pointers to the elements to be compares, but your predicate assumes the elements are passed by value (or at leas that is what I assume you mean by taking the integers by value).
My advice is to never cast a function pointer. It comes with so much more than a value that has to be reinterpreted. For example, parameter type information and parameters being read from the stack, and if the caller passes one type and the callee reads another type from the stack, then you may have screwed up the stack. So, never cast a function pointer, but let the caller pass the expected data and reinterpret it inside the called function instead. That means that all your qsort predicates should return a int and take two void-pointers, and then you cast the void-pointers inside the function.