I came across this kind of a declaration.
typedef int (*func) (int,int,int);
What is the meaning and use of this?
I came across this kind of a declaration.
typedef int (*func) (int,int,int);
What is the meaning and use of this?
It defines func
as type for function which accepts 3 integers and returns integer.
This is helpful when you pass functions as callbacks or put function addresses into arrays or something like that.
It defines a type func
which is a pointer to a function returning an int
and taking 3 int
arguments.
An example of using this would be:
typedef int (*func) (int, int, int);
int foo(int a, int b, int c) {
return a + b * c;
}
...
// Declare a variable of type func and make it point to foo.
// Note that the "address of" operator (&) can be omitted when taking the
// address of a function.
func f = foo;
// This will call foo with the arguments 2, 3, 4
f(2, 3, 4);
A more realistic scenario might be having a bunch of functions that have the same return type and taking the same type/number of arguments, and you want to call different functions based on the value of some variable. Instead of having a bunch of if
-statements or a large switch/case
you could place the function pointers in an array and use an index to call the appropriate function.
That's the typedef'd name. It reads as: func is a pointer to a function that takes three ints and returns an int.
You can see more on this link