Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a typedef for function pointers

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 <???> ?

like image 673
SetSlapShot Avatar asked Jun 14 '12 17:06

SetSlapShot


People also ask

What is typedef for function pointer?

typedef is a language construct that associates a name to a type. myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; myfunc f; // compile equally as void (*f)(); As you can see, you could just replace the typedefed name with its definition given above.

How do you typedef a function?

A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function. Given below are the steps to implement typedefs in a Dart program.

Can we typedef a function in C?

The typedef is a keyword used in C programming to provide some meaningful names to the already existing variable in the C program. It behaves similarly as we define the alias for the commands. In short, we can say that this keyword is used to redefine the name of an already existing variable.


1 Answers

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 
like image 129
Oliver Charlesworth Avatar answered Oct 05 '22 12:10

Oliver Charlesworth