Jump to content

  • Log In with Google      Sign In   
  • Create Account

Casting Arguments in Function Pointers


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
1 reply to this topic

#1 KingofNoobs   Members   -  Reputation: 301

Like
0Likes
Like

Posted 05 December 2012 - 04:52 AM

Hello,

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

I wonder as I wander...

http://www.davesgameoflife.com


Sponsor:

#2 Brother Bob   Moderators   -  Reputation: 8575

Like
2Likes
Like

Posted 05 December 2012 - 05:27 AM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS