Sign in to follow this  

Casting Arguments in Function Pointers

Recommended Posts

KingofNoobs    305

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.

-Dave Ottley

Share this post

Link to post
Share on other sites
Brother Bob    10344
Ignoring what is strictly correct, because it can be quite tricky when it comes to casting and I'm not sure what is actually correct or not, but 1 is likely to behave as you expect, and 2 is likely to break when the size of a pointer is difference from the size of an integer.

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.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this