Wednesday, 11 January 2017

Passing a function as an argument to a function

In C, while calling a function to carry out a task, usually the data for the function is sent as arguments. But it is also possible to send a function itself as an argument. The following program defines two functions add( ) and sub( ) which are passed as an argument to another function.

//C program to pass function as an argument
#include<stdio.h>
int add(int,int);
int sub(int,int);
void f_calling_f(int,int,int (*)(int,int));
void main ()
{
  clrscr();
  printf("Passing function to function\n");
  f_calling_f(10,20,add);
  f_calling_f(10,20,sub);
  getch();
}
void f_calling_f(int a,int b,int (*f)(int,int))
{
   f(a,b);
}
int add(int a,int b)
{
   printf("\nThe result of addition of %d and %d is %d\t",a,b,a+b);
}
int sub(int a,int b)
{
   printf("\nThe result of subtraction of %d and %d is %d\t",a,b,a-b);
}


/*
OUTPUT
------------
Passing function to function
                                                                                
The result of addition of 10 and 20 is 30                                       
The result of subtraction of 10 and 20 is -10
*/                                                             

No comments:

Post a Comment