Typedef type of function pointer

I want to declare a type of pointer that points to a function, so I'm trying:

typedef void (*print)(void); works great

void (*print)(void); p is a ponter variable, not a type.

typedef (void) (*print)(void); expected error identifier or '(before' void

typedef void (*)(void) Print;

error: expected '=,', ';,' asm or '_ attribute _ before' Print.

My question is:

  • Should I use typedef to declare a type of function pointer?

  • Why typedef (void) (*print)(void); not this way? what does () mean?

  • Why can't I write like this: typedef void (*)(void) Print ?

+4
source share
2 answers

The right way:

 typedef void (*print_function_ptr)(void) 

and using it to declare a variable / parameter:

 print_function_ptr p; 
  • You do not need a typedef command to declare a variable. You can directly write void (*p)(void) to declare a variable p that points to a function that takes void and returns void . However, to declare an alias / type name for a function pointer, typedef is a tool.

  • This does not mean that this is not a valid C syntax.

  • Because this is not how C. works. Typedefs in C mimics how variables are declared or defined.

+11
source
  • No, you do not need to use typedef to create an object of type "function pointer":

     void somefunc(void (*pointer)(void)) { (*pointer)(); pointer(); } 

    However, there is no way to create a name for a type other than using typedef . I suppose you could use macro hacking to generate a "function pointer", but after the macro has expanded, you will get a "function pointer":

     #define PTR_FUNC(func) void (*func)(void) void somefunc(PTR_FUNC(pointer)) { ... } 
  • The designation (void) as a type name is incorrect. You do not write: (int) x; and expect to declare a variable x - this is a type. Same thing with the notation you use in your typedef .

  • You cannot write typedef void (*)(void) Print; because this is not a valid C syntax. You also cannot write typedef [32] int name; either is not a valid C syntax.

+3
source

Source: https://habr.com/ru/post/1500744/


All Articles