Function Pointer as Argument in C

Function Pointer as Argument :

The function itself cannot be passed as an argument to another function.However, by utilising a function pointer, we can pass the reference to a function as a parameter.As the function parameter is supplied as a pointer that contains the address of arguments, this technique is known as a call by reference. .

Function Pointer as Argument

Syntax :

(type) (*pointer_name)(parameter);

Example :

Run
#include<stdio.h>
//function to display even numbers
int help(void (*show)())  
{  
    for(int i=0;i<=10;i+=2)  
    {  
        show(i);  
    } 
    return 0;
} 
//printing the value
void print(int val)  
{  
    printf("%d ",val);  
}  
int main()  
{  
    void (*show)(int);       
    printf("The even values are :");  
    help(print);  
    return 0;  
}

Output :

The even values are :0 2 4 6 8 10

Point to remember for Function Pointer as Argument in C :

Example :

Run
#include<stdio.h>
// function to swap two integer
void help(int *a, int *b) 
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int val1 = 15, val2 = 30;
   
    help(&val1, &val2);    //passing values to function
   
    printf("value of val1 = %d\n", val1);
    printf("Value of val2 = %d", val2);
    return 0;
}

Output :

value of val1 = 30
Value of val2 = 15

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