Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Question About Function Pointer In C

There's the following declarations:

void qsort(void *lineptr[], int left, int right, int (*comp)(void *, void *));
int numcmp(char *, char *);
int strcmp(char *s, char *t);

Then, somewhere in the program there is the following call:

  qsort((void**) lineptr, 0, nlines-1, 
                    (int (*)(void*,void*))(numeric ? numcmp : strcmp));

(Ignore the first three arguments and numeric).

I ask what is this:

(int (*)(void*,void*))(numeric ? numcmp : strcmp)

I understand that qsort is expecting a "pointer to function that gets two void pointers and returns an int" as it's 4th argument but how what's written above satisfies that? It seems to me like some sort of cast because it is made of two parentheses, but that would be a very odd cast. Because it takes a function and makes this function a "pointer to function that gets two void pointers and returns an int". Which is meaningless.
(I followed here the rule that a type type in parenthesis before a variable promotes the variable to that type).

So I think I just get it wrong, maybe someone can tell me how to read this, what's the order?

like image 248
Ori Popowski Avatar asked Apr 16 '09 15:04

Ori Popowski


1 Answers

What's happening here is indeed a cast. Lets ignore the ternary for a second and pretend that numcmp is always used. For the purpose of this question, functions can act as function pointers in C. So if you look at the type of numeric it is actually

(int (*)(int*,int*))

In order for this to be properly used in qsort it needs to have void parameters. Because the types here all have the same size with respect to parameters and return types, it's possible to substitute on for the other. All that's needed is a cast to make the compiler happy.

(int (*)(void*,void*))(numcmp )
like image 106
JaredPar Avatar answered Oct 14 '22 07:10

JaredPar