Q:

Function Pointer example program in C programming

0

Function Pointer example program in C programming

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;

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C language important programs ( Advance Programs )

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Stringizing Operator in C | How to print a variabl... >>
<< C program to get current system date and time in L...