Course Content
Programming in C
About Lesson

Functions themselves aren’t variables, but it is possible to define pointers to functions, which can be assigned, placed in arrays, passed to functions, returned by functions, etc.

int (*cmp)(void *, void *);

declares a pointer cmp to a function that has two void * arguments and returns an int. In the following code, we use the same function pointer to first point to the string library function strcmp and compare two strings, then point it to user-defined function numcmp and compare two double values passed as strings.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int numcmp(char *, char *); 

int main()
{
  int (*cmp)(void *, void *);

  cmp = (int (*)(void *, void *))strcmp;
  printf("%d\n", (*cmp)("hello", "world"));
  printf("%d\n", (*cmp)("hello", "hello"));

  cmp = (int (*)(void *, void *))numcmp;
  printf("%d\n", (*cmp)("123", "-12"));
  printf("%d\n", (*cmp)("123.45", "123.45"));

  return 0;
}

int numcmp(char *s1, char *s2)
{
  double num1, num2;
  num1 = atof(s1);
  num2 = atof(s2);
  if (num1  num2)
    return 1;
  return 0;
}

As cmp is the pointer to a function, *cmp is the function, so

(*cmp)("hello", "world")

makes the function call. The parentheses are needed so that the components are correctly associated.

Scroll to Top