Consider the following code snippet:
typedef int (*FNPTR)(const void* p1, const void* p2);
typedef struct {
char name[100];
int age;
} Person_t;
void display(Person_t p[], size_t size)
{
for (size_t i = 0; i < size; i++) {
printf("%s: %d\n", p[i].name, p[i].age);
}
}
int compare_by_age(const void* p1, const void* p2)
{
return ((Person_t *)p1)->age - ((Person_t *)p2)->age;
}
int compare_by_name(const void* p1, const void* p2)
{
return strcmp(((Person_t *)p1)->name, ((Person_t *)p2)->name);
}
FNPTR compare(int choice)
{
return (choice == 0) ? compare_by_age : compare_by_name;
}
int main()
{
Person_t p[] = {
{"John", 21},
{"Albert", 23}
};
size_t size = sizeof(p)/sizeof(p[0]);
qsort(p, size, sizeof(p[0]), compare(1));
display(p, size);
...
}
One disadvantage of this program is, if we keep adding fields to the Person structure, then we have to write "n" compare functions. Is it possible to create and return relevant compare function inside the compare itself, based on the choice(without adding "n" compare functions). Something similar to C++ lambads so that we can create and return a function within another function in C (or any other better logic).