Passing Pointer to Function in C

Passing Pointer to Function in C

In this article, I am going to discuss Passing Pointer to function in C with Examples. Please read our previous articles, where we discussed Pointer to Array of functions in C.

Pointer to function in C

Pointers can also be passed as an argument to a function like any other argument. Instead of a variable, when we pass a pointer as an argument then the address of the variable is passed instead of the value. So any change made to the pointer by the function is permanently made at the address of the passed variable. It is also known as call by reference in C.

#include<stdio.h>
int addition ();
int main ()
{
    int result;
    int (*ptr) ();
    ptr = &addition;
    result = (*ptr) ();
    printf ("The sum is %d", result);
}

int addition ()
{
    int a, b;
    printf ("Enter two numbers: ");
    scanf ("%d %d", &a, &b);
    return a + b;
}

Output:

Pointer to function in C

Points to Remember:
  • A function pointer points only to code, not to data.
  • Using function pointers we do not allocate de-allocate memory.
  • To get functions’ address a function’s name can also be used.
  • We can have an array of function pointers like normal pointers.
  • In place of switch case, we can use the Function Pointer.
Example to understand Pointer to function
#include <stdio.h>
void salaryhike (int *var, int b)
{
  *var = *var + b;
}

int main ()
{
    int salary = 0, bonus = 0;
    printf ("Enter the employee current salary:");
    scanf ("%d", &salary);
    printf ("Enter bonus:");
    scanf ("%d", &bonus);
    salaryhike (&salary, bonus);
    printf ("Final salary: %d", salary);
    return 0;
}

Output:

Passing Pointers to Function in C

In the next article, I am going to discuss Character Pointer in C language. Here, in this article, I try to explain Pointer to function in C. I hope you enjoy this Pointer to function in C article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *