Reputation: 3540
I know what typedef does but this statement seems to be puzzling me.
typedef int (*funcptr)();
This declaration
funcptr pf1,pf2
Means this
int (*pf1)(),(*pf2)();
But then how to use pf1
and pf2
in program. How to take input of these values.
And what is the use of it.
Upvotes: 0
Views: 112
Reputation: 41
pf1 and pf2 are function pointers now...if you want them to point to a function you should write pf1=yourfunctionname..
Upvotes: 1
Reputation: 122383
This is a very artificial example code, but it illustrates how to use typedef
function pointers.
#include <stdio.h>
typedef int (*funcptr)();
int return1(void){return 1;}
int return2(void){return 2;}
int main()
{
funcptr pf1, pf2;
pf1 = return1;
pf2 = return2;
printf("%d, %d\n", pf1(), pf2());
return 0;
}
Output: 1, 2
Upvotes: 1
Reputation: 726539
Your typedef
defines a type for a function pointer. Taking a "value" of a function pointer has no meaning: it is a pointer to a piece of executable code; you need to call it to make it useful.
You call a function through a pointer in the same way as if it were a function known to you by name, i.e. by appending a parenthesized list of parameters to the pointer.
Here is what you can do with pf1
or pf2
:
// These functions return an int and take no parameters.
// They are compatible with funcptr
int function5() {
return 5;
}
int functionAsk() {
int res;
printf("Enter a value: ");
scanf("%d", &res);
return res;
}
// This function does not know what fp1 does, but it can use it
void doSomething(funcptr fp1) {
int res = fp1();
printf("Function returned %d", res);
}
// Here is how you can call doSomething with different function pointers
pf1 = functionAsk;
doSomething(pf1);
pf2 = function5;
doSomething(pf2);
Note how in the last four lines two calls of doSomething
perform different tasks based on what you pass: the first call prompts the user for an entry, while the second call returns five right away.
Upvotes: 1