Does anyone know how to understand the fourth line of the code shown below?
typedef short Signal;
typedef struct Event Event;
typedef struct Fsm Fsm;
typedef void (*State)(Fsm *, Event const *);
Does anyone know how to understand the fourth line of the code shown below?
typedef short Signal;
typedef struct Event Event;
typedef struct Fsm Fsm;
typedef void (*State)(Fsm *, Event const *);
It declares State
as a typedef
for void (*)(Fsm *, Event const *)
.
void (*)(Fsm *, Event const *)
is a function pointer, pointing to a function that takes two arguments, Fsm *
and Event const *
, and returns void
.
More information: How do function pointers in C work? and Typedef function pointer?
Let's go through the typedefs one by one:
short
. Now you can write Signal xyz = 0;
and it would be equivalent to writing short xyz = 0;
struct
types without the struct
keyword. In other words, you can now write Fsm myFsm;
instead of writing struct Fsm myFsm;
State
that corresponds to a void
function pointer taking a pointer to Fsm
and a pointer to Event
.The syntax may be a little tricky because of all the parentheses and the name being typedef-ed not being at the end of the declaration. You can tell it's a type definition for a function pointer, because the name of the type is in parentheses, and is prefixed with an asterisk. The rest of the typedef
looks very much like a function signature, so the result is easy to read.