Taylor
Taylor

Reputation: 3

Understanding this complex declaration

static void (* __set_malloc_handler(void (*__f)()))();

I think __set_malloc_handler is a function pointer, and it points to a function which also needs a function pointer. But, I have no idea how to understand the whole statement. How does it work?

Upvotes: 0

Views: 84

Answers (2)

hurturk
hurturk

Reputation: 5444

__set_malloc_handler is a function that takes a "function pointer to a void function" and returns a "function pointer to a void function". Keyword static makes it only visible to the current file.

Upvotes: 1

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

It's easier to understand with some aliasing.

//pointer to function taking no arguments and void return
typedef void(*function_pointer)();

//function taking "function_pointer" and returning "function_pointer"
function_pointer __set_malloc_handler(function_pointer __f);

To read something like that, I recommend the right-left rule. It's what I always use. There's also a spiral rule, but I get annoyed when it doesn't form a perfect spiral and I get too distracted by that to focus. You probably won't have that issue.

The explanation on either page is more thorough, but here's a crash course.

Essentially, read these symbols as:

  1. * = "pointer to"
  2. (...) = "function taking ..."
  3. [...] = "array of size ..."

Read to the right until you find a ) that didn't have a matching ( yet. Then read to the left until you find a ( to match it. Start reading right again. If you hit the end of the line on the right, you finish reading to the left.

To the immediate right of the identifier __set_malloc_handler is an open parenthetical (, meaning it is a function. Everything from that to the matching ) is the parameter type. I'd recommend ignoring it at first and coming back to it later. Step by step:

       __set_malloc_handler(...)    //function taking ...
     (*__set_malloc_handler(...))   //and returning a pointer
     (*__set_malloc_handler(...))() //to a function taking no arguments
void (*__set_malloc_handler(...))() //that returns void

Looking at the parameter, we have:

     (*__f)   //pointer
     (*__f)() //to function taking no arguments
void (*__f)() //and returning void

Upvotes: 1

Related Questions