how can we store Function in pointer


So far u have seen that a pointer stores address of variable, array, structure n many else. But there is one another property of a pointer to store or to refer a complete function, i.e., a pointer is referring a function and then this pointer can be used simply as we use our function.

An example for this is as:

#include<iostream>
#include<conio.h>

using namespace std;
int fun()
{
     cout<<"Enigma of C++";
}

main()
{
      int (*p)() =fun;   //Here the pointer p can now be used in place of function fun
      (*p)();                //This is the way how this pointer can be used
      getch();
}

Another example by using a parameterized function (function with arguments) can be:

#include<iostream>
#include<conio.h>

using namespace std;
int fun(int a,int b)
{
    if(a>b)
      return a;
    return b;
}

main()
{
      int(*p)(int,int) =fun;           //see how the pointer is declared  
      int d= (*p)(4,3);                   //value returned by the function is stored in d;    
      cout<<d;
      getch();
}

Points to remember:

1.        Always keep in mind that at the time of declaration of the pointer its type should same as the return type of the function. This means that if the return type of the function is int then the pointer is declared as :
int (*p)()
If function has a void data type then pointer will be declared as:
void (*p)()
2.       Before the declaration of pointer the function must be declared once in the scope of pointer
Consider this example:
#include<iostream>
#include<conio.h>

using namespace std;
main()
{
      int(*p)()=fun;
      (*p)();
      getch();
}
int fun()
{
     cout<<"Enigma of C++";
}
The above code will generate an error of function not defined.
To correct the program include the declaration of function as int fun (); before the declaration of the pointer.

About the author

Admin
Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus. Aenean fermentum, eget tincidunt.

1 comment:

Template by Clairvo Yance
Copyright © 2012 Enigma of IT and Blogger Themes.