需要在已经有一个 typedefining 的情况下添加 * 吗?

huangapple go评论56阅读模式
英文:

Do we need to add * when typedefining with one already

问题

当编写这个C结构时:

typedef struct node_s* node_t;

struct node_s {
  int value;
  node_t next;
};

每当我们定义一个类型为 node_t 的变量时,我们不需要添加一个指针 * 吗?

例如:

node_t f(node_t node) {
...
}

这样,f 接收一个节点并返回一个节点。

英文:

When writing this C struct:

typedef struct node_s* node_t;

struct node_s {
  int value;
  node_t next;
};

Anytime we define a variable of type node_t we don't need to add a pointer * ?

For example:

node_t f(node_t node) {
...
}

such that f receives a node and returns one.

答案1

得分: 1

node_t 是对 struct node_s * 的别名,所以

node_t p;

等价于

struct node_s *p;

node_t f( node_t node )

等价于

struct node_s *f( struct node_s *node )

说了这些之后...

一般来说...

在typedef背后隐藏指针不是一个好主意,除非你还提供了一个API,从用户那里隐藏了类型的“指针性”。

如果你的类型的用户必须显式地对其进行解引用或访问成员以正确使用它,那么不要隐藏指针或结构的特性在typedef背后。

英文:

node_t is an alias for struct node_s *, so

node_t p;

is exactly equivalent to

struct node_s *p;

and

node_t f( node_t node )

is exactly equivalent to

struct node_s *f( struct node_s *node )

Having said all that...

It's generally not a good idea to hide a pointer behind a typedef unless you also provide an API that hides the "pointer-ness" of the type from the user.

If the user of your type has to explicitly dereference it or access a member in order to use it properly, then don't hide the pointer-ness or the struct-ness behind a typedef.

huangapple
  • 本文由 发表于 2023年6月4日 23:55:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定