Function Pointers

Function Pointers

·

2 min read

Pointer allows the ability to store an address of a variable. Additionally, an address of a function can be stored. Just as there is a pointer to the basic types like int, char, etc, there is a pointer to a function, and a variable is needed to be declared to store the address of a function.

Syntax of a function pointer

return_type (*pointer_name)(argument/s); whereby:-

  • return_type: the function return type.
  • *pointer_name: name of the pointer.
  • arguement/s: number of arguments taken by the function the pointer points to.

Examples

char(*ptr)(char) A pointer that points to a function that returns a character and takes one character argument.

int(*ptr)(int int); A pointer that points to a function that returns an integer and takes two int arguments

Application of Function Pointer

One of the usages of a function pointer is Callback Function. It is a function that calls another function.

Example

The following program prints a name using a callback function.

#include <stdio.h>

void print_name(char *name, void (*f)(char *))
{
    if (name != NULL && f != NULL)
    {
        f(name);
    }
}
void print_name_uppercase(char *name)
{
    unsigned int i;

    printf("Hello, my uppercase name is ");
    i = 0;
    while (name[i])
    {
        if (name[i] >= 'a' && name[i] <= 'z')
        {
            putchar(name[i] + 'A' - 'a');
        }
        else
        {
            putchar(name[i]);
        }
        i++;
    }
}
void print_name_as_is(char *name)
{
    printf("Hello, my name is %s\n", name);
}

int main()
{
    print_name("Bob", print_name_as_is);
    print_name("Bob Dylan", print_name_uppercase);
    printf("\n");
    return 0;
}

Explanation

  1. The program has two functions that take one string argument and return a void (nothing);
  2. The two functions print the passed string on its parameters.
  3. The third function (print_name()) is a void function that has two arguments:-
  • a string (char *name)
  • a pointer variable (void (f)(char )) - which points to a function that returns a void and takes one string argument.
 void print_name(char *name, void (*f)(char *))
{
    if (name != NULL && f != NULL)
    {
        f(name);
    }
}

The function that is passed within the bracket of the pointer (f()) takes a string argument that is why "name" is placed. In other words, it is calling back to a function that takes a string argument. The function is called in main:-

print_name("Bob", print_name_as_is);

"Bob" representing the string argument that the function takes (char *name) print_name_as_is - a called function (the function called in another function (print_name)) is called and executes. The function pointer in the printname() function necessitate the operation.

Hopeful that this write-up will be of help to you.