I was reading a mergeSort from standard library in c and found that it has a compare function as an argument(i.e void msort(void *base, size_t nitems, size_t size, int (*compar)(const void , const void)) when it's defined). However, in actual use when the msort function is called, compar function didn't have an argument passed to it(even though it had two parameters, which are (const void *, const void *) as parameters. look the ff code snippet and I would appreciate how it's possible for a function with parameters to be used without arguments in the time it's called??
#include <stdio.h>
#include <stdlib.h>
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
msort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
This is a so called a function pointer: you're basically passing the function
cmpfunc()as a parameter, which will then be used by themsort()function internally, with the proper arguments.Function pointers are the precursors of function closures.
To be more clear: the reason why it has no arguments is because you don't know them yet.
Let me explain:
cmpfunc()serves to compare 2 elements and tell which one precedes the other. Butmsort()will need to do many different comparisons, since it has to iterate over all the elements ofvalues[]. Therefore, internallymsort()is going to select 2 elements at a time, let's call themxandy, compare themcmpfunc(x, y)and swap them if needed.