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. Means that pointers will not store any values rather than they store the addresses where the value exist.
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.
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;
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, with 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 it. 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.
or you can call this way also;
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;
void SayHello ()
printf ("Hello, World!");
void PrintMessage (char *message)
printf ("%s", message);
void main ()
void (*pfn1) ();
void (*pfn2) (char *message);
pfn1 = SayHello;
pfn2 = PrintMessage;
pfn2 ("\nGood Day!");