Introduction to using function pointers in C (or C++)

[Page updated: 2008-11-08 (hesa)]

Why function pointers anyway?

In C (C++) you can use function pointers to implement plugins or to change, at one place, the function to call, no matter where you use the function (through the pointer), or to remove “expensive” if statements in tight loops.

But instead of spending too much energy on talking we’ll continue with an example. Throughout this introduction we’ll use a feedback functionality. Your program wants to give feedback to the user and instead of using a variable which we switch over to choose the right feedback implementation we are going to use function pointers. Depending on what environment the user is using we can use a gui feedback or console based feedback. Later on, in introduction to writing plugins, we’ll dive into more practical use of them pointers.

Let’s settle for a feedback function prototype (stripped down functionality, no variable sized argument list etc):

int default_feedback(char *str)

The function returns an int. The first argument is the string to print. Let’s add an implementation to the function:

int default_feedback(char *str)

{

return fprintf(stdout, “%s”, str);

}

Please note, we haven’t used function pointers yet.We can use the function by calling it like this:

default_feedback(“Ordinary call\n”);

So far so good. Let’s define our first function pointer. Let’s create a variable feedback_fun that stores the pointer to the function we want to call.

int (*feedback_fun)(char *str) ;

We can see that this looks a bit like the function above. We’ve just added some “(*” and an extra “)”. What the live above says is: the function pointed to by feedback_fun returns an int and takes char *str as argument. Piece of cake, isn’t it? We can now use the variable to store the address to a function we want to use.

Let’s store the address in our function pointer:

feedback_fun = default_feedback ;

and call the function through the function pointer

feedback_fun(“Called using function pointer call\n”);

Was that it? Yes, neat isn’t it? So if we turn this into a program, including a main function and some comments, we get this:

/*
* Copyright (c) 2008, Henrik Sandklef
*
*/

#include <stdio.h>

/*
* Global varible poiting to th feedback function choosen
*
*/
int (*feedback_fun)(char *str) ;

/*
* Name:         default_feedback
* Args:           str – string to print
* Description:  Prints a string to given file
*/
int
default_feedback(char *str)
{
return fprintf(“%s”, str);
}

int main(int argc, char **argv)
{

/* Set feedback_fun to point at default feedback function */
feedback_fun = default_feedback ;

/* Call the  default_feedback in the ordinary way */
default_feedback(“Ordinary call\n”);

/* Call the default_feedback through the feedback_fun variable */
feedback_fun(“Called using function pointer call\n”);

return 0;
}

2 responses to “Introduction to using function pointers in C (or C++)

  1. Then why is’t this program working ??

    #include
    #include
    void main()
    {
    void concat(char *, char *);
    void len(char *);
    char s1[20],s2[20];
    int ch, length;
    clrscr();
    while(1)
    {
    printf(“MAIN MENU\n”);
    printf(“1.Length of the string\n”);
    printf(“2.Concatination of two strings\n”);
    printf(“3.Exit”);
    scanf(“%d”,&ch);
    switch(ch)
    {
    case 1:
    printf(“Enter a string =”);
    scanf(“%s”,s1);
    printf(“\n Length of %s = %d”,s1,len(s1));
    break;
    case 2:
    printf(“Enter the first string = “);
    scanf(“%s”,s1);
    printf(“Enter the second string = “);
    scanf(“%s”,s2);
    concat(s1,s2);
    printf(“The cancatinated string is = %s “,s1);
    break;
    case 3:
    exit();
    default:
    printf(“\n Invalid option”);
    }
    }
    }

    int len(char* s)
    {
    while(*s!=”)
    {
    length++;
    s++;
    }
    return(length);
    }

    void cancat(char* s1,char* s2)
    {
    while(*s1 != ”)
    s1++;
    while(*s2 != ”)
    {
    *s1=*s2;
    s1++;
    s2++;
    }
    *s1=”;
    }

  2. it has vomited the symbol \ and 0.. please add it while conditions and assigning variables.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s