C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs



Home » C programs » Advance C programs

Function Pointer example program in C programming.






A function pointer is a pointer variable that can store address of a function and then using the function pointer we can call initialized function in our program.

Function Pointer Example using C program

Declaration of function pointer

return_type (*fun_pointer_name)(argument_type_list);

Initialization of function pointer

fun_pointer_name= &function_name;
fun_pointer_name= function_name;

Calling of function pointer

*(fun_pointer_name)(actual_argument_list);

Declaration with Initialization

return_type (*fun_pointer_name)(argument_type_list)= &function_name;
Consider the example
/*function pointer example in c.*/

#include <stdio.h>


//function: sum, will return sum of two
//integer numbers
int addTwoNumbers(int x,int y)
{
	return x+y;
}

int main()
{
	int a,b,sum;
	
	//function pointer declaration
	int (*ptr_sum)(int,int);
	//function initialisation
	ptr_sum=&addTwoNumbers;
	
	a=10;
	b=20;
	
	//function calling
	sum=(*ptr_sum)(a,b);
	
	printf("Sum is: %d\n",sum);
	
	return 0;
}

    
    
    Sum is: 30

int addTwoNumbers(int x,int y);

This function will take two integer arguments and returns addition of those numbers.

int (*ptr_sum)(int,int);

This is the declaration of the function pointer for addTwoNumbers function.

ptr_sum=&addTwoNumbers;

This statement is initializing the function pointer with address of function addTwoNumbers.

(*ptr_sum)(a,b);

This statement is the calling the function ptr_sum and ptr_sum will point to the addTwoNumbers.








You may also be interested in...

C/C++ Tips and Tricks...

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.


Comments and Discussions