typedef in c: struct or function reference?

两盒软妹~` 提交于 2020-05-14 07:49:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!