Page 180 - C-Language
P. 180
Chapter 25: Function Pointers
Introduction
Function pointers are pointers that point to functions instead of data types. They can be used to
allow variability in the function that is to be called, at run-time.
Syntax
• returnType (*name)(parameters)
• typedef returnType (*name)(parameters)
• typedef returnType Name(parameters);
Name *name;
• typedef returnType Name(parameters);
typedef Name *NamePtr;
Examples
Assigning a Function Pointer
#include <stdio.h>
/* increment: take number, increment it by one, and return it */
int increment(int i)
{
printf("increment %d by 1\n", i);
return i + 1;
}
/* decrement: take number, decrement it by one, and return it */
int decrement(int i)
{
printf("decrement %d by 1\n", i);
return i - 1;
}
int main(void)
{
int num = 0; /* declare number to increment */
int (*fp)(int); /* declare a function pointer */
fp = &increment; /* set function pointer to increment function */
num = (*fp)(num); /* increment num */
num = (*fp)(num); /* increment num a second time */
fp = &decrement; /* set function pointer to decrement function */
num = (*fp)(num); /* decrement num */
printf("num is now: %d\n", num);
https://riptutorial.com/ 156

