3

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 ?

8
  • 2
    What's wrong with using the_name_1= void(*)(...); using the_name_2 = the_name_1;? Commented Mar 9, 2022 at 14:20
  • Nothing wrong with that. Just trying to figure out if a one-liner is possible. Commented Mar 9, 2022 at 14:20
  • 2
    one-liner is often possible, but more often not "good design" as it's less expressive and easy to make or miss a mistake. Commented Mar 9, 2022 at 14:50
  • Why would you want to do it, though? Both aliases will just name the same type and will be able to be used interchangeably, so it doesn’t provide any type safety to have both. The only reason I can imagine is adding a compatibility alias, but even then typedefing one name to the other would be preferable. Commented Mar 9, 2022 at 14:53
  • That’s not the comma operator. Commented Mar 9, 2022 at 15:03

2 Answers 2

11

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)(...);
Sign up to request clarification or add additional context in comments.

2 Comments

I see. I'll write that in 2 lines then :-D
@PinkTurtle precisely as stated in the ISO CPP core guidelines
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.