Ad

Friday, July 13, 2007

Pointers to Function

Function Pointers is a rather confusing yet powerful feature of C++ programming language. Even if you have programming for a while I bet you have seen nothing like it, simply because they aren't’t needed in everyday programming.

Their most common use is in writing compilers and interpreters.

The main theory behind function pointers is, just like the contents of a variable can be accessed by a pointer, much the same way functions can also be invoked (called) by referencing it by a pointer to that function.

Although variables and functions are two separate identities, both of these are stored at some memory address which can be pointed (and hence accessed) by a pointer.

Going in detail of the working of function pointers will only confuse you so we skip that for now and move on to a simple example program.

The function defined in the program is made as simple as possible to reduce confusions. Please note that the program only illustrates how function pointers are declared and used but program doesn't’t serve any practical purpose.

  // -- Function Pointers --
  // Example program to illustrate how
  // pointer to function are declared
  // and used
  #include<iostream.h>

  // function prototype
  void func (void);

  void main(void)
  {
   // note the declaration of
   // of the pointer.
   // pointer is declared with void data type
   // because function's return
   // type is void, the void in the
   // parenthesis is due to the function
   // taking no (void) argument
   void (*func_ptr) (void);

   // just as array name without indices
   // gives the address, same way
   // function name without parenthesis
   // gives the address of the function
   func_ptr=func;

   cout<<"Function accessed directly:\n";
   func();

   cout<<"Function accessed via pointer:\n";
   (*func_ptr)();
  }

  void func(void)
  {
   cout<<"Simplest of the simple function\n\n";
  }

Good-Bye!

Related Articles:

No comments:

Post a Comment

You are free to comment anything, although you can comment as 'Anonymous' it is strongly recommended that you supply your name. Thank You.

Please don't use abusive language.