Home > database >  How can I declare multiple function pointer types in one typedef declaration?
How can I declare multiple function pointer types in one typedef declaration?

Time:03-10

I can do

typedef int a, b;

but I can't do something like

typedef void(*the_name_1, *the_name_2)(...);

Is there a way do to typedef 2 function pointer types at the same time ?

CodePudding user response:

Multiple declaration in C/C is misleading as * is linked to variable and not to the type:

typedef int a, *b, (*c)();

static_assert(std::is_same_v<int, a>);
static_assert(std::is_same_v<int*, b>);
static_assert(std::is_same_v<int (*)(), c>);

So your one-liner would be

typedef void(*the_name_1)(...), (*the_name_2)(...);

CodePudding user response:

Let’s ignore the typedef for a moment.

void (*the_name_1, *the_name_2)(...);

Keeping in mind that C declarations (and C as well, mostly) follow the rule of ‘declaration reflects use’, this says that (*the_name_1, *the_name_2) is an expression that can be invoked with whatever arguments, returning void. This makes the_name_2 a pointer to a function taking whatever and returning void, but it tells you nothing about the type of the_name_1, other than that it should be possible to dereference.

That is why Jarod42’s answer has you write the argument list twice. This way you say that both the_name_1 and the_name_2 can be dereferenced, then invoked with whatever, giving you void. It’s entirely analogous to

char foo[42], bar[69];

The only difference typedef makes is that the names declared become names of types that the otherwise-declared variables would have.

  • Related