Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone please explain to me a complicated function pointer type in C++

Tags:

Can anyone tell me what is the type of the parameter for the function f?

int f(void (*(int,long))(int,long)) {} 

I am getting a similar type to this in when trying to compile some variadic template heavy code (my own wrapper around std::thread)...

like image 446
tohava Avatar asked Mar 02 '15 21:03

tohava


People also ask

What is a pointer to function type in C?

A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.

What is function pointer type?

A function pointer, also called a subroutine pointer or procedure pointer, is a pointer that points to a function. As opposed to referencing a data value, a function pointer points to executable code within memory.

What is complicated declaration and evaluation in C?

Complicated declarations in C. Redeclaration of global variable in C. Internal Linkage and External Linkage in C. Different ways to declare variable as constant in C and C++ Variable length arguments for Macros.

Can a pointer refer to any type?

Every pointer is of some specific type. There's a special generic pointer type void* that can point to any object type, but you have to convert a void* to some specific pointer type before you can dereference it. (I'm ignoring function pointer types.) You can convert a pointer value from one pointer type to another.


2 Answers

The declaration

int f(void (*(int,long))(int,long)) {} 

declares a function f returning int and taking as argument a pointer to a function that takes int, long parameters and returns a pointer to a function that returns void and takes parameters int, long. Using a typedef for the innermost function pointer, this becomes more readable:

typedef void (*fptr)(int, long); int f(fptr(int, long)); 

Or with a named parameter,

int f(fptr handler(int, long)); 

This is perfectly valid code, but it is odd to see in compiler output because it uses a special syntax rule: in a function parameter list, a function type declarator declares a function pointer parameter. That is to say,

int f(fptr   handler (int, long)); // is equivalent to int f(fptr (*handler)(int, long)); 

...and you'd expect the compiler to use the lower, general form.

like image 149
Wintermute Avatar answered Sep 21 '22 17:09

Wintermute


It's a function taking a pointer to a function that takes int and long as parameters and returns a function taking int and long as parameters and returns void. Probably a lot clearer if you use a trailing return type and name the function:

int f(auto g(int, long) -> void (*)(int, long)); 
like image 44
David G Avatar answered Sep 17 '22 17:09

David G