Sunday, August 28, 2011

Implement of Callback Functions in C







Function Pointers provide the concept of callback functions. Implement a callback function using function pointer with an example of qsort algorithm.
The function receives the pointer to a comparison-function which takes void-pointers to two field-items, evaluates their ranking and returns the result coded as an int. So every time the sort algorithm needs a decision about the ranking of two items, it just calls the comparison-function via the function pointer.
#include  // due to: qsort
#include  // printf
// comparison-function for the sort-algorithm
// two items are taken by void-pointer, converted and compared
int CmpFunc(const void* _a, const void* _b)
{
	// you’ve got to explicitly cast to the correct type
	const float* a = (const float*) _a;
	const float* b = (const float*) _b;
	if(*a > *b) return 1; // first item is bigger than the second one -> return 1
	else
		if(*a == *b) return 0; // equality -> return 0
		else return -1; // second item is bigger than the first one -> return -1
}
// example for the use of qsort()
void QSortExample()
{
	float field[100];
	for(int c=0;c<5;c++)
		scanf("%f",&field[c]);
	// sort using qsort()
	qsort((void*) field, /*number of items*/ 5, /*size of an item*/ sizeof(field[0]),
	/*comparison-function*/ CmpFunc);
	// display first ten elements of the sorted field
	printf("The first five elements of the sorted field are ...\n");
	for(int c=0;c<5;c++)
		printf("element #%d contains %.0f\n", c+1, field[c]);
	printf("\n");
}
int main(){
	QSortExample();
	getchar();getchar();
	return 0;
}

No comments:

Post a Comment