Callback Function in C
In the C programming language, a callback function is a function that is passed as an argument to another function and is invoked at some later point in time.
The following are some crucial ideas to comprehend regarding callback functions in C:
1. Function Pointers: In C, function pointers implement callback functions. A variable containing a function's address is known as a function pointer. Another function can be told to call a specific function later by sending a function reference to it as an argument.
2. Flexibility and Customization: Callback functions offer a mechanism to adjust a function's behavior without changing its source code. A function can carry out various activities depending on the particular requirements or environment by enabling users to submit their callback functions.
In event-driven programming, callback functions are frequently employed when actions are prompted by user input or system events. For instance, a callback function linked with a button in a graphical user interface (GUI) program is called to handle an event when that button is pressed.
3. Callback Function Signature: The function that expects a callback must declare the callback's signature, including the argument list and return type. The calling function calls the callback function and passes it the necessary parameters.
4. Callback Registration: A callback function must be registered or provided to the function that will call it to be used. Usually, to do this, the function pointer is passed as an argument to the registration function.
C's callback functions offer a robust framework for creating dynamic behavior, customization, and event-driven programming. They allow functions to adapt to various contexts and user-defined needs, increasing flexibility and extensibility in software development.
Here is a C program that uses callback functions to show how to do it:
Code:
#include <stdio.h>
// Callback function type
typedef void (*Callback)(int);
// Function that takes a callback function as an argument
void perform operation(int num, Callback callback) {
printf("Performing operation with %d\n", num);
callback(num);
}
// Callback function to square the number
void squareCallback(int num) {
int result = num * num;
printf("Square of %d is %d\n", num, result);
}
// Callback function to cube the number
void cubeCallback(int num) {
int result = num * num * num;
printf("Cube of %d is %d\n", num, result);
}
int main() {
int number = 5;
printf("Number: %d\n", number);
printf("Calling performOperation with squareCallback:\n");
performOperation(number, squareCallback);
printf("Calling performOperation with cubeCallback:\n");
performOperation(number, cubeCallback);
return 0;
}
In this program, a function pointer defines a callback function of type Callback. An integer num and a callback function of type Callback are required parameters for the performOperation function. It then calls the callback method while performing an action on the supplied number and sending the number as a parameter.
The next step is to create two callback methods that square and cube the provided integer accordingly. By executing performOperation with several callback functions inside the primary function, we show how to utilize callback functions.
The program will execute the operation using the supplied number when it is run, call the relevant callback function, and show the outcome.
![Callback Function in C](https://static.tutorialandexample.com/c/callback-function-in-c1.png)
By offering several operations to be carried out on the number in this example, the callback functions squareCallback and cubeCallback customize the behavior of the performOperation function.
Other than this, callback functions are also helpful in so many other scenarios. Here is a C sorting program example that employs a callback function for specific comparisons:
Code:
#include <stdio.h>
#include <string.h>
// Callback function type for custom comparison
typedef int (*CompareCallback)(const void*, const void*);
// Bubble sort function that takes a callback function for comparison
void bubbleSort(void* arr[], int size, CompareCallback compare) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (compare(arr[j], arr[j + 1]) > 0) {
// Swap elements if the comparison is true
void* temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Custom comparison function for sorting integers in ascending order
int compareInt(const void* a, const void* b) {
int num1 = *((int*)a);
int num2 = *((int*)b);
return num1 - num2;
}
// Custom comparison function for sorting strings in alphabetical order
int compareString(const void* a, const void* b) {
const char* str1 = *(const char**)a;
const char* str2 = *(const char**)b;
return strcmp(str1, str2);
}
int main() {
// Sort an array of integers
int intArray[] = {7, 2, 5, 1, 9};
int intSize = sizeof(intArray) / sizeof(int);
// Casting the integer array to void pointer array
void* intPtrArray[intSize];
for (int i = 0; i < intSize; i++) {
intPtrArray[i] = &intArray[i];
}
bubbleSort(intPtrArray, intSize, compareInt);
printf("Sorted Integers: ");
for (int i = 0; i < intSize; i++) {
int* value = (int*)intPtrArray[i];
printf("%d ", *value);
}
printf("\n");
// Sort an array of strings
const char* strArray[] = {"apple," "banana," "grape," "cherry"};
int strSize = sizeof(strArray) / sizeof(const char*);
// Casting the string array to void pointer array
void* strPtrArray[strSize];
for (int i = 0; i < strSize; i++) {
strPtrArray[i] = (void*)&strArray[i];
}
bubbleSort(strPtrArray, strSize, compareString);
printf("Sorted Strings: ");
for (int i = 0; i < strSize; i++) {
const char* value = *(const char**)strPtrArray[i];
printf("%s ", value);
}
printf("\n");
return 0;
}
This program shows how to sort data using the bubble sort method. It contains a general bubble sort method that may use a callback function for specific comparisons to order arrays of any data type. Using the included compareInt and compareString callback methods, the program demonstrates the sorting of both strings and integers.
Output:
![Callback Function in C](https://static.tutorialandexample.com/c/callback-function-in-c2.png)