为什么我们要在 C 中如此频繁地 typedef 结构? [英] Why should we typedef a struct so often in C?

查看:34
本文介绍了为什么我们要在 C 中如此频繁地 typedef 结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过很多由如下结构组成的程序

I have seen many programs consisting of structures like the one below

typedef struct 
{
    int i;
    char k;
} elem;

elem user;

为什么经常需要它?有什么具体原因或适用领域吗?

Why is it needed so often? Any specific reason or applicable area?

推荐答案

正如 Greg Hewgill 所说,typedef 意味着您不再需要到处编写 struct.这不仅可以节省按键次数,还可以使代码更简洁,因为它提供了更多的抽象.

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

类似的东西

typedef struct {
  int x, y;
} Point;

Point point_new(int x, int y)
{
  Point a;
  a.x = x;
  a.y = y;
  return a;
}

当你不需要到处都看到struct"关键字时,它会变得更清晰,它看起来更像是在你的语言中真的有一种叫做Point"的类型.在 typedef 之后,我猜是这种情况.

becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the typedef, is the case I guess.

另请注意,虽然您的示例(和我的)省略了对 struct 本身的命名,但实际命名它在您想要提供不透明类型时也很有用.然后你会在标题中有这样的代码,例如:

Also note that while your example (and mine) omitted naming the struct itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:

typedef struct Point Point;

Point * point_new(int x, int y);

然后在实现文件中提供struct定义:

and then provide the struct definition in the implementation file:

struct Point
{
  int x, y;
};

Point * point_new(int x, int y)
{
  Point *p;
  if((p = malloc(sizeof *p)) != NULL)
  {
    p->x = x;
    p->y = y;
  }
  return p;
}

在后一种情况下,您不能按值返回 Point,因为它的定义对头文件的用户是隐藏的.例如,这是一种在 GTK+ 中广泛使用的技术.

In this latter case, you cannot return the Point by value, since its definition is hidden from users of the header file. This is a technique used widely in GTK+, for instance.

UPDATE 请注意,在一些备受推崇的 C 项目中,使用 typedef 来隐藏 struct 被认为是一个坏主意,Linux 内核可能是最著名的此类项目.请参阅Linux Kernel CodingStyle 文档的第 5 章对于莱纳斯的愤怒的话.:) 我的观点是,问题中的应该"毕竟可能不是一成不变的.

UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

这篇关于为什么我们要在 C 中如此频繁地 typedef 结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆