Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)));

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}

As others have mentioned, you don’t actually need that cast; but, without it, some compilers will emit a warning. MSVC doesn’t give a warning but clang-cl gives:

warning : incompatible function pointer types passing ‘int (const char
*, const char )’ to parameter of type ‘_CoreCrtNonSecureSearchSortCompareFunction’ (aka ‘int ()(const void
*, const void *)’)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading