Friday, August 17, 2007

Function returning a pointer to a function

Function returning a pointer to a function

void (*RetFtr())();

I am not surprised …. Because I know , I have formula to deals with. :)

Let us apply our 'magic formula' here also.

So starts with the variable name . i.e RetFptr… Kool Body … :)

RetFptr is a ..

Go to the right what we get a function taking no arguments.
So we get
function, (taking no arguments)
then go to left , what we get “*” that is pointer which is returned by the function ,Am I right , Assume , I can never be wrong… :)

so we get

which returns a pointer to ,

Now parentheses gets over;
Then go to right
What we get , it is again a function (which takes no arguments)
So we get
a function (which takes no arguments)

Now we go to left , here we find ,That function returns nothing i.e. void
that returns nothing or void.

Now we put together what we have collected as of now …. :)
So we get

RetFptr is a function, (taking no arguments) which returns a pointer to a function (which takes no arguments) that returns nothing or void.

Now we have done a good discussion , Lets do some practical …. :)

Example

void show()
{
printf("\n show()");
}


void (*RetFptr())()
{
return show;
}

Now, I need a pointer to RetFptr. How can I declare that?

I want a pointer to a function (*myFptr)() which, returns a function pointer,
Here I can write like this using the same formula… i.e Go right & Left .

(*(*myFptr)()) () of a function that takes no arguments and returns nothing (void)

void (*(*myFptr)()) ();

Here the below code does the same this what I have discussed above.
In main , I should have a pointer which can hold a RetFptr is a function, (taking no arguments) which returns a pointer to a function (which takes no arguments) that returns nothing or void.


#include
void show()
{
printf("\n show function ()\n");
}

void (*RetFptr())()
{
return show;
}

int main(int argc, char* argv[])
{
void (*(*ptr_to_fptr_ret_fptr)())();

ptr_to_fptr_ret_fptr = RetFptr;

ptr_to_fptr_ret_fptr()();

return 0;
}

All the example program i tested in my home pc,.GCC version 2.96
@ the Dollar prompt if you type gcc -v , you will get get some message , here i type that message
"gcc -v Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specsgcc version 2.96 20000731 (Red Hat Linux 7.1 2.96-98)"
here my compile version = 2.96,
and my OS = Red Hat Linux 7.1 2.
if you have any question regarding this program , Feel free to mail me.
hara.sahu@gmail.com
cheer,
sahu

No comments: