我们为什么要使用C的typedef一个结构如此频繁? [英] Why should we typedef a struct so often in C?

查看:130
本文介绍了我们为什么要使用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?

推荐答案

由于格雷格Hewgill表示,自定义类型意味着你不再需要编写结构所有的地方。这不仅节省了按键,它也可以使code清洁剂,因为它提供了一个稍微多费一点抽象。

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;
}

变得更清洁,当你不需要看到结构关键字的所有的地方,它看起来更象是否真的有一个在你的语言称为点式。其中,后的typedef ,是我猜的情况。

另外请注意,虽然省略了您的示例(和我)命名结构本身,其实它的命名也是有用的,当你想提供一个不透明的类型。然后,你就会有code这样的标题,例如:

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 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;
}

在后一种情况下,你不能通过值回点,因为它的声明是从头文件的用户隐藏。这是 GTK + 广泛使用的技术,例如。

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

更新注意,也有备受推崇的ç项目中这样使用的typedef 来隐藏结构被认为是一个坏主意,Linux内核可能是最知名的此类项目。见Linus的气话 Linux内核文件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天全站免登陆