问题
Analyzing some part of software written by someone else, I found the following line of code:
typedef const struct rpc_method *(*super_t)(RPC*);
Ok, i know,
typedef rpc_method *(*super_t)(RPC*);
declares a type super_t which is a function pointer...
I also know what typedef struct means, but the combination of the two??
Is it a struct with a single entry???
And what means const in this context??
Could it be that const and struct are exchanged???
Nevertheless seems to compile with my gcc eabi.
回答1:
If a declaration without typedef would declare a variable IDENTIFIER as an object of type TYPE, a declaration with typedef declares IDENTIFIER as type alias for type TYPE (i.e., the same type that the variable in the same declaration without the typedef would have).
So given that
struct rpc_method const*(*super_t)(RPC*);
declares super_t as a pointer to a function taking a pointer to RCP and returning a pointer to struct rpc_method const,
typedef struct rpc_method const*(*super_t)(RPC*);
declares super_t as a type alias for the type of the above pointer (to a function taking a pointer to RCP and returning a pointer to struct rpc_method const).
The const in the above declaration qualifies the target of the return type, whether you write it as struct rpc_method const* or const struct rpc_method* (putting the qualifer at the right hand side of the type works makes it more consistent with qualifiers put in other linkes of a chained pointer E.g., in struct foo const * const * volatile bar the last two const and volatile have to be at the right hand side of their *, while the first const could go left of struct foo with no change of semantics.
More details:
https://stackoverflow.com/a/57793519/1084774
来源:https://stackoverflow.com/questions/61453705/typedef-in-c-struct-or-function-reference