Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++: using a typedef'd function pointer to *declare* a function

Tags:

c++

c

I need to typedef a function pointer type to create an array of pointers, and to declare a large number of functions that will end up in the array. However, I can't find a way to do both of these things at the same time: either I can get pointers for the array, or I can declare functions, but not both.

Any ideas on how I can get this code to work without lots of pointless text, or am I stuck with repeating the entire function signature for every function I need to declare? Thanks.

#include <stdio.h>

// declare a fn ptr type named 'myfunc'
typedef void (*myfunc)(int);

//myfunc A,B,C,etc;  **doesn't work, because of the (*)
void A(int);         // does work, but becomes very tedious

int main() {
   myfunc B = A;     // actually assigning a large 2D array
   A(42);
   B(43);
}

void A(int foo) {
   printf("%d\n", foo);
}
like image 762
QF0 Avatar asked Sep 06 '25 03:09

QF0


1 Answers

In C++ you may use

std::remove_pointer_t<myfunc> A, B, C;

Or declare one typedef for the function type and another for the pointer to function type:

typedef void myfunc(int);
typedef myfunc * myfuncptr;
myfunc A, B, C;

The latter works in C and C++.

like image 71
Oktalist Avatar answered Sep 07 '25 21:09

Oktalist