Tuesday, 3 April 2018

Pointers to Functions

1. Cpp allows functions to be referenced by a pointer.
2. A pointer to a function must be declared to be a pointer to the datatype returned by the functions like void , int , float and so on....
3. In addition , the argument type of the function must also be specified when a pointer is declared.
4. The argument declaration is a list of a formal argument separated by commas and enclosed in parenthesis.
5. The general Syntax of a pointer to a function is
    Returntype (*variable) (list of parameters);
   Ex : void (*ptr) (float a, float b, float c);
   In the above declaration , a pointer to a function returns void and takes formal arguments of two float and one int.
 Ex : float (*ptr) (char a, double b, int c, float d)
 In the above declaration , a pointer to a function returns a floating point value and takes the formal argument of char , double , int and float type.
6. After the declaration of pointer to a function , the address of the function must be assigned to a pointer.

WAP to find sum of three numbers and average using pointer to function.

void calavg(int a, int b, int c);
void (*ptr)(int a, int b, int c);
void main( )
int a1, b1, c1;
clrscr( );
cout<<"\n\tEnter Any three Values";
getch( );
void calavg(int a, int b, int c)
int sum;
float avg;
cout<<"\n\n\tSum of three nos is--->"<<sum;
cou<<"\n\n\tAverage is--->"<<avg;

Enter Any three Values 2.23  45
Sum of three nos is--->80
Average is--->26.66666

WAP to demonstrate how a pointer to a function is declared to perform simple arithmetic operation addition, subtraction, multiplication and division of two nos.

void calop(int a, int b);
void (*ptr)(int a, int b)
void main( )
int a1,b1;
clrscr( );
cout<<"\n\n\tEnter Any two nos";
getch( );
void calop(int a1,int b1)
cout<<"\n\n\tAddition is---><<(a1+b1);
cout<<"\n\n\Subtraction is--->"<<(a1-b1);
cout<<\n\n\tMultiplication is--->"<<(a1*b1);
cout<<"\n\n\tDivision is---><<(a1/b1);

Enter Any two nos 12  6
Addition is--->18
Subtraction is--->6
Multiplication is--->72
Division is--->2

1 comment:

Popular Posts


Android (21) AngularJS (1) Assembly Language (2) Books (10) C (75) C# (4) C++ (81) Data Strucures (4) Downloads (1) Engineering (13) FPL (17) Hadoop (1) HTML&CSS (38) IS (25) Java (87) Leet Code (4) PHP (20) Python (214) R (69) Selenium Webdriver (2) Software (14) SQL (27)