Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointer expression

Tags:

c++

pointers

So I've got the following expression:

int (*f1(int(*a)(int, int))) (int, int);

and I'm trying to make sense out of it, but it's confusing. I figured out that "a" is a pointer to a function which takes 2 arguments(int, int). Then f1 seems to be a pointer to another function that takes 2 int arguments. But what's confusing me is how f1 relates to a.

Can someone give me some hints or properly explain what the above expression is doing?

like image 647
Diez Avatar asked Jan 13 '18 12:01

Diez


People also ask

What is function pointer with example?

In C, we can use function pointers to avoid code redundancy. For example a simple qsort() function can be used to sort arrays in ascending order or descending or by any other order in case of array of structures. Not only this, with function pointers and void pointers, it is possible to use qsort for any data type.

What is function pointer in C++ with example?

It is basically used to store the address of a function. We can call the function by using the function pointer, or we can also pass the pointer to another function as a parameter. They are mainly useful for event-driven applications, callbacks, and even for storing the functions in arrays.

How does a function pointers work C++?

Function Pointers in C and C++ A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior.


1 Answers

The tip in C is to read a declaration as it were an expression. This is this famous symmetrie that make C elegant.

How to read it? following the operators precedence rules:

  1. *a: if I dereference variable a;
  2. (*a)(int,int): and then call it with two integers;
  3. int (*a)(int,int): then I get an integer;

So a is a pointer to a function taking two ints as parameter and returning an int.

Then:

  1. f( int(*a)(int,int) ) if I call f with the argument a;
  2. *f( int(*a)(int,int) ) and then I dereference the result;
  3. (*f( int(*a)(int,int) )(int,int) and then call this result with 2 int as argument
  4. int (*f( int(*a)(int,int) )(int,int) I get an int

So f is a function taking an a as argument and returning a pointer to a function that take two ints as argument and returning an int. So f return type is the same as its argument return type. It could have been simpler:

using ftype = int(*)(int,int);
ftype f( ftype a);
like image 88
Oliv Avatar answered Nov 15 '22 18:11

Oliv