C Programming – Function Pointers in C

Pointers plays a major role in C Programming. Writing a code with pointers is more error prone than the code without pointers. Understanding pointers is bit difficult.

The simple thing about pointer is, a pointer is a variable which holds an address, like variables holds a value. That means, pointers will not store any values rather than they store the addresses where the value exist.

Pointer to a function

As we can store address of a variable in a pointer variable; it is also possible to store address of a function in the pointers. Through this article, we are going to discuss this.

First, declare a pointer variable which will hold an address of a function. Keep in mind that, the pointer to function variable should have the same number and type of arguments as the function you are going to store the address of it. And the return type also should match. That means, it should have the same syntax of the function declaration;

void (*pfn)();

Have you noticed, function pointer variable name is enclosed in “()”? This is important. Otherwise, it treats as a function which is returning a void * pointer. That said, there is a difference between these below declarations;

void *pfn();
void (*pfn)();

The first one is, a function returning a void * pointer. This is nothing but (void *) pfn(). This is not a function pointer.

The second one is, a function pointer. Which points to a function, has no arguments, and no return value.

Second, assign the function address to the pointer variable.

pfn = SayHello;

Where SayHello is the function with NO arguments and return type is void; which matches the syntax of the function pointer declaration.

When you use the function name, without parentheses “()”; it returns the address of of the function. Whereas, when you use the function name with “()”, it executes the function. From above statement, we should assign the function pointer to the pointer variable; hence simply mention the function name “SayHello“. Otherwise, it throws the below error;

void value not ignored as it ought to be

Third, Invoke the function using pointer variable.

pfn();

or you can call this way also;

(*pfn)();

So, we are calling the function through it’s pointer. It is similar to calling the function; “SayHello()“.

Here is the sample code; which demonstrates, function pointers in C;

#include <stdio.h>

void SayHello ()
{
    printf ("Hello, World!");
}

void PrintMessage (char *message)
{
    printf ("%s", message);
}

void main ()
{
    // observe the declaration of these pointers; matches with function declaration
    void (*pfn1) ();
    void (*pfn2) (char *message);
    
    pfn1 = SayHello;
    pfn2 = PrintMessage;
        
    pfn1 ();
    pfn2 ("\nGood Day!");
}

//Malin

C Programming – Function Pointers in C

Leave a Reply

Your email address will not be published.

Scroll to top