Add numbers using function pointer
In this tutorial we will be learning how to add the two numbers using pointer in c programming.
Recommanded Articles : Function pointer | Function pointer reference
How to add two numbers using function pointer ?
#include<stdio.h> int sum (int n1,int n2); int main() { int num1 = 10; int num2 = 20; int result; int *(*ptr)(int,int); ptr = ∑ result = (*ptr)(num1,num2); printf("Addition : %d",result); return(0); } int sum (int n1,int n2) { return(n1 + n2); }
Output :
Addition : 20
Explanation :
- Write whole program using normal function call i.e sum(num1,num2);
- After you write whole code, just erase line in which we have called function and replace that line with following line –
Step 1 : Declaring Pointer Variable
int *(*ptr)(int,int);
means –
Declare pointer variable which is capable of storing address of function which have integer as return type and which takes 2 arguments
Step 2 : Initializing function Pointer
ptr = ∑
using above statement we will be storing address of function in function pointer
Step 3 : Calling Function
result = (*ptr)(num1,num2);
It will call function sum(num1,num2). Above statement will be elaborated as –
result = (*ptr)(num1,num2); result = (*&sum)(num1,num2); result = (*&sum)(num1,num2); result = (sum)(num1,num2); result = sum(num1,num2);