Search code examples

Passing the function *cmp(const *void, const *void) as a parameter in C and using it to create a queue?

I have an assignment from a professor that I don't fully understand. This is our specified function header:

PQueue createQueue( int (*cmp)(const void*a, const void*b) ) {

I can't find the documentation for cmp to understand what the function itself does; what does it do?

And beyond that, how can I refer to it within createQueue when I write the code to create the queue?


  • cmp is parameter of createQueue, it is a function pointer passed in by the caller. Typically cmp it will return:

    • a negative integer if *a is less than *b
    • 0 if *a is equal to *b
    • a positive integer if *a is greater than *b

    This is the convention used by the standard library qsort, which sorts an array when given some comparison function.

    As a concrete example, we can get the behavior

    int a = 1, b = 2, c = 2;
    cmp(&a, &b); // returns < 0
    cmp(&b, &c); // returns 0
    cmp(&b, &a); // returns > 0

    if we define cmp as

    int cmp(const void * a, const void * b) {
        const int * a_int_ptr = (const int *)a;
        const int * b_int_ptr = (const int *)b;
        int a_value = *a_int_ptr;
        int b_value = *b_int_ptr;
        return a_value - b_value;