Functional programming in C

June 22, 2012

Let's play around with functional programming in C. We'll write an eval function that, given a pointer to a binary function, and given two inputs, applies the inputs to the function and returns the result.

We'll want to print to standard output with printf:

#include <stdio.h>

We'll also want to convert command line arguments into integers with atoi:

#include <stdlib.h>

Let's start with some basic arithmetic functions:

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

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

int mult(int x, int y) {
  return x * y;

We'll need a way to evaluate an arbitrary binary function given two arguments:

int eval(int (*f)(int, int), int x, int y) {
  int result = f(x, y);
  return result;

Now we can pass a binary function, f, and a couple of inputs, x and y, to eval, which will apply the inputs to the function and return the result.

Let's put it together so we can run it from the command line:

int main(int argc, char *argv[]) {

  int x = atoi(argv[1]);
  int y = atoi(argv[2]);

  int result = eval(mult, x, y);

  printf("mult(%d, %d) = %d\n", x, y, result);

  return 0;

This post is literate C. Try running it with codedown:

$ curl -s |
  codedown c |
  gcc -o fp-c -xc -
$ ./fp-c 6 7
mult(6, 7) = 42