Pointers to Functions - C Pointer

C examples for Pointer:Function Pointer

Introduction

The following code defines three functions with same parameter and return types and uses a pointer to a function to call each of them in turn.

Demo Code

#include <stdio.h>

int sum(int, int);
int product(int, int);
int difference(int, int);

int main(void)
{
  int a = 10;            
  int b = 5;             
  int result = 0;        
  int (*pfun)(int, int);              // Function pointer declaration

  pfun = sum;                         // Points to function sum()
  result = pfun(a, b);                // Call sum() through pointer
  printf("pfun = sum             result = %2d\n", result);

  pfun = product;                     // Points to function product()
  result = pfun(a, b);                // Call product() through pointer
  printf("pfun = product         result = %2d\n", result);
  pfun = difference;                  // Points to function difference()
  result = pfun(a, b);                // Call difference() through pointer
  printf("pfun = difference      result = %2d\n", result);
  return 0;//from  w  w w.j av a2  s  . com
}
int sum(int x, int y){
  return x + y;
}

int product(int x, int y){
  return x * y;
}

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

Result


Related Tutorials