Pointer to a function

December 20th, 2009 by Kevin | Posted under C Programming.

In a C program, we can have a pointer to a function which gives us a pointer to a specific block of executable code. The code to be executed is determined at the run time depending on the address assigned to the function pointer. This helps us create programs which can emulate the polymorphic capabilities of any object oriented programming language.

A function pointer is declared as

return-type (* function-pointer-name)(type arg1, type arg2. ...);

Following code excerpt shows an example how a function pointer can be used to design polymorphism in C.

struct MediaObject_
{
   ...........
   void (*play)(int ); /* declaration of a function pointer */
}MediaObject;

playAudio(int sound)
{
   ............
}

playVideo(int sound)
{
   ............
}

void main()
{
   MediaObject mediaObj;
   MediaType mediaType = getMediaType();

   if(mediaType == AUDIO)
   {
       mediaObj.play = playAudio; /* function pointer assignment */
   }
   else if(mediaType == VIDEO)
   {
      mediaObj.play = playVideo; /* function pointer assignment */
   }

   /* play function pointer can be used for audio or video*/
   mediaObj.play(100);
}

Care should be taken to provide some value to your function pointer before it is actually used. Since a function pointer is a variable, you will not get any compilation errors if you do not initialize it but your program will give an ugly crash at runtime.

 

Related Posts:

Tags: , ,

Comments

One Response to “Pointer to a function”
  1. sm says:

    good information

    [Reply]

Do you have any comments on Pointer to a function ?

Spam protection by WP Captcha-Free