Monday, 16 January 2017

Calling functions using pointer

Pointers in C language makes it unique and offers effective programming capabilities. Using pointers to call functions in C is the best way to call a function dynamically.


//C program to call functions using pointers
#include<stdio.h>
int add(int,int); //function prototype
int sub(int,int);
main()
{
 int a,b;
 int (*ptr1)(int,int)=add;    //declaring pointer to a function and assigning the address of add function
 int (*ptr2)(int,int);

 clrscr();
 ptr2=sub;          //assigning the address of function sub
 printf("\nEnter two numbers to add\n");
 scanf("%d%d",&a,&b);

 printf("\ncalling function using pointer\n");
 printf("-----------------------------------\n");
 (*ptr1)(a,b);         //calling function using ptr1 variable
 ptr2(a,b);             //another way to call function using pointer
 getch();
}
int add(int a,int b)
{
 printf("The result of addition is %d\n",a+b);
}
int sub(int a,int b)
{
  printf("The result of subtraction is %d\n",a-b);
}

/*
OUTPUT
---------
Enter two numbers to add
5
6

calling function using pointer
-----------------------------------
The result of addition is 11
The result of subtraction is -1
*/

No comments:

Post a Comment