How to create a typedef for function pointers

SetSlapShot picture SetSlapShot · Jun 14, 2012 · Viewed 86.8k times · Source

I think it would be easier to use function pointers if I created a typedef for a function pointer, but I seem to be getting myself tripped up on some syntax or usage or something about typedef for function pointers, and I could use some help.

I've got

int foo(int i){ return i + 1;}
typedef <???> g;
int hvar;
hvar = g(3)

That's basically what I'm trying to accomplish I'm a rather new C programmer and this is throwing me too much. What replaces <???> ?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Jun 14, 2012

Your question isn't clear, but I think you might want something like this:

int foo(int i){ return i + 1;}

typedef int (*g)(int);  // Declare typedef

g func = &foo;          // Define function-pointer variable, and initialise

int hvar = func(3);     // Call function through pointer