Register | Sing In

New posts

Stacks in C programming Linked Lists in C programming File Input/Output in C programming Check prime numbers in C Programming C Programming Enumeration C Programming Union

Archives

2013-10 2013-09 2013-08

Pointers to Functions in C Programming

September 5, 2013 Posted by: GPA Views: 561 0 comments

Problem

Write simple program that illustrate the use of pointers to functions in C. 

Solution

In this article, you will learn how to use Pointers to function. C provides a special feature of pointer to a function. A pointer to a function contains the address of the function in memory. Pointers to functions can be passed to functions, returned from functions, stored in arrays and assigned to other function pointers. To illustrate the use of pointers to functions, we present a modified version of the add, sub mul and div two numbers program.

Example:

   

#include <stdio.h>
#include <stdlib.h>
//prototype of functions
void operationwithNumbers(float (*mathematicaloperation)(float a, float b),char arithmeticoperation,float a,float b);
float sum(float a,float b);
float sub(float a,float b);
float division(float a,float b);
float mul(float a,float b);
//main function
int main(int argc, char *argv[])
{
  //declare variables for a and b
   float a=50;
   float b=2;
   //call function
   operationwithNumbers(sum,'+',a,b);//call function operationwithNumbers with pointer to function sum
   operationwithNumbers(sub,'-',a,b);//call function operationwithNumbers with pointer to function sub
   operationwithNumbers(mul,'*',a,b);//call function operationwithNumbers with pointer to function mul
   operationwithNumbers(division,'/',a,b);//call function operationwithNumbers with pointer to function division
   system("PAUSE");
  return 0;
}
//parameter mathematicaloperation is a pointer to the mathematical operation function that calculate sum sub div or product of two nummbers
void operationwithNumbers(float (*mathematicaloperation)(float a, float b),char arithmeticoperation,float a,float b){
 printf("Result of arithmetic operation %c of two numbers = %.3lf\n",arithmeticoperation,(*mathematicaloperation)(a,b));
}
float sum(float a,float b){
   return a+b;
}
float sub(float a,float b){
   return a-b;  
}
float division(float a,float b){
   return a/b;
}
float mul(float a,float b){
   return a*b;  
}

Output

pointers to functions in c programming

Download this example

0 Comments...

Leave a Reply

Please, Sing In to leave a Reply for this material.



Online Chat

LiveZilla Live Help

Popular posts

Function strtok in C programming Check prime numbers in C Programming C Programming Union Linked Lists in C programming File Input/Output in C programming C Programming Enumeration

RSS-subscribe

New materials

Subscribe