In C++, just as we can have pointers to variables, we can have pointers to functions as well.
The general syntax of a pointers to a functions is:
return-type (*pointer-name) (list of parameter);
For example:
In the above declaration, a pointer to a function returns
void
and takes the two formal arguments of float
and int
types respectively.
After declaring a pointer to a function, the address of the function must be assigned to a pointer as follows:
p = &function-name;
where p is a pointer variable.
Through pointer to function, the function is called as follows:
where, x and y are actual parameters, and
A is a variable in which the function’s return value is stored,
p is a pointer name which points to the function
A is a variable in which the function’s return value is stored,
p is a pointer name which points to the function
Let us illustrate pointer to function with a programming example as follows:
The output of the above program would be:
s = 30.8
In the above program:
- The statement:
declares a pointerp
which is a pointer to function - The statement:
assigns the address of functionadd
top
, i.e., now pointerp
points to functionadd
- The statement:
calls the function which is pointed byp
(i.e., add) and then assigns the returned value of function tos
- It is worthwhile to note here that if in pointer to function declaration we skip the bracket in which pointer name is is written the C++ compiler interprets it as a function which returns a pointer type value. For example, if in above program we write:
then this statement meansp
is a function which returns pointer and the pointer points tofloat
type data. i.e., function returns a pointer tofloat
0 comments:
Post a Comment