22

I would like to declare a variable of type pointer to function returning pointer to function. Essentially what the following does, but without any typedefs:

typedef void (*func)();
typedef func (*funky_func)();

funky_func ptr;

I tried the following

(void (*)()) (*ptr)();

but it gives an "undeclared identifier"-error for ptr (probably due to completely different parsing). Being not that well-versed in the intricacies of parsing C++, I'd like to know if this is even possible and if yes, how to do it.

(Please consider this an entirely artificial scenario for the sake of curiosity, without any practical reason. I am perfectly aware that in practice typedefs are the way to go here, if using function pointers at all.)

0

2 Answers 2

30

You can have a look at the declaration of signal() which is a function taking a void(*)() and returning one of those. The variable ptr can be declared like this:

void (*(*ptr)())()

The notation is a bit awkward and clearly inside out. It may be easier to use trailing return types:

auto (*ptr)() -> void (*)()

... or, of course, use trailing return types all the way through:

auto (*ptr)() -> auto (*)() -> void
Sign up to request clarification or add additional context in comments.

Comments

28

The general rule of C (and C++) declarations is: if you type the declaration as an expression, it will have the declaration's type.

So, you want a pointer to function which returns pointer to function returning void.

Let's say we have such a pointer, ptr. How to get void out of it?

  1. Dereference ptr, getting a function returning pointer to function returning void: *ptr

  2. Call the function, getting a pointer to function returning void: (*ptr)()

  3. Dereference that pointer, getting a function returning void: *(*ptr)()

  4. Call that function, getting void: (*(*ptr)())()

Now just turn this into a declaration:

void (*(*ptr)())();

P.S. I know other have answered in the meantime (and I've upvoted). But I wanted to show the generic process to arrive at the declaration form.

1 Comment

I wanted to show the generic process to arrive at the declaration form. --this excellent way, I could quickly grasp from your answer. Thanks!

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.