Home > Software design >  Ways to declare a function pointer in C as a class attribute
Ways to declare a function pointer in C as a class attribute

Time:09-17

This question is motivated by the post C : class that has a pointer to a function as an attribute

I came up with a similar problem that the one described in there. And it is the way on how to correctly declare a function pointer. This seems pretty usefull for me, as you can declare a function pointer and then assign it later to make the program much more general. The three ways that are described in the post are the following ones:

  1. The first case is obviously wrong, it declares a function that returns a void pointer void* func().
  2. The way upvoted and tagged as solution. It does not work for my particular case void *(func)(). This case seems to be the same as the previous one.
  3. The third comment and the one working for me void (*func)(). This seems clear to me that the definition is a pointer to a void function.

My question is summarized as: What is the main difference between the second and third declaration?

CodePudding user response:

The answer on your link had a typo, HolyBlackCat correct it. The correct version is indeed void (*func)().

If you want to go truly general you can use std::function<void()>. This way you can store any kind of callable object: functions, lambdas, callable classes.

CodePudding user response:

It's to do with precedence rules. It's the no different than the difference between 1 (2)*3 and (1 2)*3.
Applied to declarations in C/C

void *(func)()

Parses in to void * (func)() -> void * func(), a function that returns a void*.

To change the precedence, we bind the "*" to the identifier.

void (*func)()

Parses to a pointer to a function that returns void and takes void. This is because now the compiler must parse the label and the pointer together, and thus knows that "func" is pointer to something.

It's all because "()" has a higher precedence than "*"

more information can be found here

  • Related