c pass function pointer code example

Example 1: pass the pointer in C

// passing a pointer to function in C
// It increaments the salary of an employee


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

Example 2: how to use a pointer as a parameter in c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void add(int* a, int* b, int* c)
{
    *c = *a + *b;
}
int main()
{
	int a, b, c;
	a = 3;
	b = 5;
	add(&a, &b, &c);
	printf("%d", c);
}

Example 3: c function pointer

//Declaration of a pointer to a function that takes an integer 
//and returns an integer.
int (*f_ptr)(int);

//Assignment of a function foo to the function pointer f_ptr declared above.
f_ptr = foo;

//Calling foo indirectly via f_ptr, passing the return value of foo to r.
int r = f_ptr(v);

//Assigning an address of a function to the function pointer f_ptr,
//then calling foo by dereferencing the function pointer.  
f_ptr = &foo;
int r = (*f_ptr)(v);

Tags:

C Example