How to Create a Typedef for a Function Pointer in C?
In C, a function pointer is a variable that stores the address of a function that can later be called through that function pointer. The typedef is a keyword used to create an alias or alternative name for the existing data types. In this article, we will learn how to create a typedef for a function pointer in C.
Typedef for a Function Pointer in C
To create a typedef for a function pointer, we specify the return type of the function, followed by an asterisk (*) and the name of the typedef in parentheses. We also need to specify the number and types of parameters of the function pointer.
Syntax
typedef return_type (*alias_name)(parameter_types and numbers....);
Here, return_type is the return type of the function alias-name is the alias we want to give to the function pointer type and parameter_types are the types of the parameters the function takes.
C Program to Create a Typedef for a Function Pointer in C
// C Program for how to create a Typedef for a Function
// Pointer
#include <stdio.h>
typedef int (*Operation)(int, int);
int add(int a, int b) { return a + b; }
// Function to the subtract two integers
int subtracts(int a, int b) { return a - b; }
// Driver Code
int main()
{
// Declare function pointers using typedef
Operation operationAdd = add;
Operation operationSubtract = subtracts;
printf("Addition result: %d\n", operationAdd(20, 9));
printf("Subtraction result: %d\n",
operationSubtract(20, 9));
return 0;
}
// C Program for how to create a Typedef for a Function
// Pointer
typedef int (*Operation)(int, int);
int add(int a, int b) { return a + b; }
// Function to the subtract two integers
int subtracts(int a, int b) { return a - b; }
// Driver Code
int main()
{
// Declare function pointers using typedef
Operation operationAdd = add;
Operation operationSubtract = subtracts;
printf("Addition result: %d\n", operationAdd(20, 9));
printf("Subtraction result: %d\n",
operationSubtract(20, 9));
return 0;
}
Output
Addition result: 29 Subtraction result: 11