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

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.

C Advance Programs »



Related Programs

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.