Function Pointer in C

Function Pointer :

Function pointers in C are variables that can be used to construct function calls to functions pointed by them by storing the memory address of the functions in them.

Function Pointer in C

Syntax :

return_type  (*ptr_name)  (type1, type2);

Example :

The below program is  explaining the working of function pointer in C.

Run
#include<stdio.h>

void help(int val)
{
    printf("Value of val is %d\n", val);
}
  
int main()
{
    // pointer to function declaration 
    void (*help_ptr)(int) = &help;
    (*help_ptr)(20);
  
    return 0;
}


Output :
Value of val is 20

Features of Function Pointer :

  • A function pointer, in contrast to other pointers, points to code rather than data.
    Usually, the beginning of executable code is stored in a function pointer.
  • Switch case can be substituted with a function pointer.
  • A function pointer can be supplied as an argument and can also be returned from a function, just like regular data pointers can.
  • In C, function pointers can be utilised to create calls to the functions they point to.This enables programmers to send them as parameters to functions.Callback functions are another name for such functions that are supplied as arguments to other functions.
  • Pointers are one type of value that functions can accept and return.Changes made to pointers when they are supplied as function arguments remain after the function has finished.Passing pointers to function arguments in this manner is known as pass by reference.

Examples :

Let,s see some example for better understanding the function pointer in C

Example 1

Run
#include<stdio.h>
// function to find the smmaler value between two integer
int *smaller(int *val_1, int *val_2) {
    if (*val_1 < *val_2) {
        return val_1;
    }
    return val_2;
}
int main() {
    int val_1 = 20, val_2 = 30;
    int *val;

     // calling the function
    val = smaller(&val_1, &val_2);
    printf("Smallest value is  = %d", *val);
    return 0;
}

Output :
Smallest value is  = 20

Example 2

Run
#include<stdio.h>
// function for addition of two integer
int addition(int val_1, int val_2) {
    int sum = val_1 + val_2;
    return sum;
}


int main() {
    int a, b, summation;
    a= 100;
    b= 200;
    // declaration of function pointer
    int (*fp)(int, int); 
    fp = addition;
    summation = (*fp)(a, b); 
    
    printf("Sum of two values = %d", summation);
    return 0;
}

Output :
Sum of two values = 300

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription