Function pointer as argument in CTill now, we have seen that in C programming, we can pass the variables as an argument to a function. We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments. If any change made by the function using pointers, then it will also reflect the changes at the address of the passed variable. Therefore, C programming allows you to create a pointer pointing to the function, which can be further passed as an argument to the function. We can create a function pointer as follows: In the above syntax, the type is the variable type which is returned by the function, *pointer_name is the function pointer, and the parameter is the list of the argument passed to the function. Let's consider an example: A function pointer can also point to another function, or we can say that it holds the address of another function. In the above case, we have declared a function named as 'add'. We have also declared the function pointer (*a) which returns the floating-type value, and contains two parameters of integer type. Now, we can assign the address of add() function to the 'a' pointer as both are having the same return type(float), and the same type of arguments. Now, 'a' is a pointer pointing to the add() function. We can call the add() function by using the pointer, i.e., 'a'. Let's see how we can do that: The above statement calls the add() function by using pointer 'a', and two parameters are passed in 'a', i.e., 2 and 3. Let's see a simple example of how we can pass the function pointer as a parameter. In the above code,
Output Now, we will pass the function pointer as a argument in Quicksort function "qsort". It uses an algorithm that sorts an array. In the above code,
Output Next TopicDynamic memory allocation in C |