Search code examples
cfunctioncastingfunction-pointers

Casting function pointer arguments without a helper function


void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))

Is there a way to pass, let's say strcmp to qsort without making a helper function?

I was trying to do:

qsort(..., (int (*) (const void*, const void*) (strcmp)));

Solution

  • Your attempt at the cast simply has a misplaced right (closing) parenthesis. The one at the end should be after the type of the cast. So, you can change:

    (int (*) (const void*, const void*) (strcmp))
    //                                          ^ wrong
    

    to

    (int (*) (const void*, const void*)) (strcmp)
    //                                 ^ right
    

    Alternatively, although hiding pointer types in typedef aliases is severely frowned-upon, function pointer types are an exception to that guideline. So, it is easier/clearer to define the required type for the qsort comparator first:

    typedef int (*QfnCast) (const void*, const void*);
    

    Then, you can cast to that type:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef int (*QfnCast) (const void*, const void*);
    
    int main(void)
    {
        char list[5][8] = {
            "Fred",
            "Bob",
            "Anna",
            "Gareth",
            "Joe"
        };
    
        qsort(list, 5, 8, (QfnCast)(strcmp));
        for (int i = 0; i < 5; ++i) printf("%s\n", list[i]);
        return 0;
    }