What is the Use of Function Pointer in C ?


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>

/********** Addition ***************/

int add(int a, int b)
{
int c = a + b;
return c;
}

/********** Substraction ***************/

int sub(int a, int b)
{
int c = a - b;
return c;
}

/********** Multiplication ***************/

int mul(int a, int b)
{
int c = a * b;
return c;
}

/********** Division ***************/

int division(int a, int b)
{
int c = a / b;
return c;
}

int main()

{
//function pointer with two int as an argument and retuns int value
int (*ptr)(int,int);

int sum; //to get the sum value using function pointer

int num1 = 2, num2 = 1;

printf("Number1 = %d\nNumber2 = %d\n",num1,num2);

int val1 = 50; int val2 = 20; //used with arrary of function pointer

ptr = add; //Assign the function address to function pointer

sum = (*ptr)(num1,num2); //Calling the function using function pointer

printf("Addition using function pointer = %d\n",sum);

ptr = sub; //Assign the function address to function pointer

sum = (*ptr)(num1,num2); //Calling the function using function pointer

printf("Substraction using function pointer = %d\n",sum);

//Array of 4 function pointers accepting two int arguments and returns int
int (*aptr[4])(int,int) = {add, sub, mul, division};

//Calling the appropriate function using array of function pointer
int fptrResult = (aptr[sum])(val1,val2);

printf("Result = %d",fptrResult);

getch();
return 0;
}

Related Post:

Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault ?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Kapil

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...