Advertisement Jump to content
Sign in to follow this  

Casting Arguments in Function Pointers

This topic is 2235 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


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
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
Sign in to follow this  

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!