It has been sometime since I have used this, but back when I was taking C for C++ Programmers
course in my undergraduate days, I did not know that you can pass function into a C function similar to passing functions in Javascript of other languages like Swift.
Below I am going to show how it is done using the void
type pointer. For this example I am going to run bunch of sort functions on an array of integers and compare the time it takes to run them. To make it easy to maintain and add different sorts in the future I decided to make an array of functions in C over which I loop through and call the function and pass the array of integers into it.
In the code above I created an array of functions using void *function[ NUM_SORT ]
where the array holds void*
pointers that point to the address of the function. In C you can get the address of the function by appending &
in front of it as such &selection_sort
.
Although it is now shown but above the functions are defined including a function called execute_sort
function. This takes in 5 arguments. The last one is the important one which contains the function pointer being passed. Lets see how we define the parameter signature of the execute_sort
function to take a pointer to another function and how to call that function.
As you can see we tell a function that it should expect a function as a parameter by using void (*sort_function)(int[], int)
signature. You need to specify the parameter types of the function being passed into the execute_sort
function which we did as all of the sort functions take an array of ints are their first argument and the size of the array as int as the second argument.
You can then call the function as such:
It is as simple as that. You can view the full source code I used in this example here and also find instructions on how to compile and run the code.