when we have :
int functon1(int a, int b);
int function2(int a, int b);
.....
typedef int (*callback) (int,int);
struct gate{
char name[50];
callback fptr;
};
Where did we give and alias with typedef and what the callback fptr is? Is (int ,int ) an alias to (*callback)?
Here in this statement
typedef int (*callback) (int,int);
/* now callback can be used as a type */
You are typedefing a function pointer. Here callback is a function pointer which can point to any function, that functions has to take two argument of int type and returns int
Next time when you do like
callback fptr;
that means fptr is function pointer and that can point to any function who satisfies callback declaration properties.
Next when you initializes fptr like this
struct gate var;
var.fptr = sum; /* here sum is the function which adds 2 int and returns int */
typedef is used for defining a new type.
What this typedef int (*callback) (int,int); means is that you are defining a new type named callback. You can use this type to define variables. A variable having the type callback is actually a pointer to a function which takes two ints and returns an int.
This explanation applies to your struct gate inside which you define fptr to be of type callback.
Here is a simple example:
#include <stdio.h>
int function1(int a, int b);
int function2(int a, int b);
typedef int (*callback) (int,int);
struct gate{
char name[50];
callback fptr;
};
int main(void) {
struct gate g;
g.fptr = function1;
printf("The sum is: %d\n", g.fptr(4, 5));
return 0;
}
int function1(int a, int b)
{
return a + b;
}
Running the above program shows:
The sum is: 9
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With