Sunday, November 25, 2012

Creating pointers to functions in C

If you have used a programming language that has first-class functions, that is, supports assigning functions to variables and passing them to other functions, like Python or JavaScript, you may wonder why such flexibility does not exist in C.

It is actually possible, and easy, to implement this in C. In this post, we shall go through
the process of creating pointers to functions.

The first thing to do is to note the function signature, i.e. the function's arguments and return type, who's pointer we want to create. In this example, we want to create a pointer to a function that accepts two integers and returns an integer.

int fptr(int x, int y);

The construct begins like a declaration of the actual function. The next step is to wrap the function name with a pointer syntax.

int (*fptr)(int x, int y);

At this point, fptr can act like a pointer to a function, and will accept a function assigned to it. We probably want to create a type so that we can create several pointers to functions. We therefore prepend typedef to the declaration.

typedef int (*fptr)(int x, int y);

fptr will now act like a type for pointers to functions that accept two integers and return an integer. Declaring a pointer to such a function is now a straight forward affair.

fptr f1, f2;

The following program listing demonstrates how pointers to two different functions with the same  function signature can be created, and how they are invoked within a program.

#include <stdio.h>

typedef int (*fptr)(int a, int b); /*pointer type to a function*/

int add(int x, int y)
{
  return x + y;
}

int sub(int x, int y)
{
  return x - y;
}

int main()
{
  fptr op1, op2; /*create two pointers and assign functions to them*/
  op1 = add;  
  op2 = sub;

  /*invoke the functions*/
  printf("op1 on %d and %d returns %d\n", 6, 5, op1(6, 5)); 
  printf("op2 on %d and %d returns %d\n", 6, 5, op2(6, 5));
  return 0;
}

No comments:

Post a Comment