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.

#Include<conio.h>
#include<iostream.h>
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";
cin>>a1>>b1>>c1;
ptr=&calavg;
(*ptr)(a1,b1,c1);
getch( );
}
void calavg(int a, int b, int c)
{
int sum;
float avg;
sum=a+b+c;
avg=sum/3.0;
cout<<"\n\n\tSum of three nos is--->"<<sum;
cou<<"\n\n\tAverage is--->"<<avg;
}

Output:-
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.

#include<conio.h>
#include<iostream.h>
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";
cin>>a1>>b1;
ptr=&calop;
(*ptr)(a1,b1);
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);
}

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

1 comment:

Popular Posts

Categories

Android (21) AngularJS (1) Books (3) C (75) C++ (81) Data Strucures (4) Engineering (13) FPL (17) HTML&CSS (38) IS (25) Java (85) PHP (20) Python (83) R (68) Selenium Webdriver (2) Software (13) SQL (27)