×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous 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.

Steps to Use Function Pointer in C

1. Declaration of function pointer

return_type (*fun_pointer_name)(argument_type_list);

2. Initialization of function pointer

fun_pointer_name= &function_name;
fun_pointer_name= function_name;

3. Calling of function pointer

*(fun_pointer_name)(actual_argument_list);

4. Declaration with Initialization

return_type (*fun_pointer_name)(argument_type_list)= &function_name;

Function Pointer Example Program in C

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;
}

Output:

Sum is: 30

Code Explanation

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.

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.