Fork me on GitHub

Function pointers in C example

# include <stdio.h>
# include <assert.h>

typedef float (*operation)(float, float);

float add(float n1, float n2) { return n1 + n2; }
float sub(float n1, float n2) { return n1 - n2; }
float multiply(float n1, float n2) { return n1 * n2; }
float divide(float n1, float n2) { assert(n2 != 0); return n1 / n2; }

float apply(float n1, float n2, operation f) { return f(n1, n2); }

int main(int argc, char* argv)
{
  float result;

  result = apply(3, 2, add);
  printf("%f\n", result);

  result = apply(3, 2, sub);
  printf("%f\n", result);

  result = apply(3, 2, multiply);
  printf("%f\n", result);

  result = apply(3, 0, divide);
  printf("%f\n", result);

  return 0;
}
Tags: c