繁体   English   中英

此C结构定义的优点是什么?

[英]What is the advantage of this C structure definition?

我不太明白为什么用这种方式定义这种结构。

这是有问题的代码块...

typedef struct Except_Frame Except_Frame;
struct Except_Frame {
    Except_Frame *prev;
    jmp_buf env;
    const char *file;
    int line;
    const T *exception;
}; 

为什么以这种方式定义该结构,而不是...

typedef struct {
    Except_Frame *prev;
    jmp_buf env;
    const char *file;
    int line;
    const T *exception;
} Except_Frame;

有什么优势?

如果您不使用:

typedef struct Except_Frame Except_Frame;

然后,将需要使用以下方法定义该struct

struct Except_Frame {

    // The keyword struct is necessary without the typedef
    struct Except_Frame *prev;

    jmp_buf env;
    const char *file;
    int line;
    const T *exception;
};

如果要在一个语句中定义structtypedef ,它将是:

typedef struct Except_Frame {

    // The keyword struct is necessary without the typedef
    // being defined ahead of the definition of the struct.
    struct Except_Frame *prev;

    jmp_buf env;
    const char *file;
    int line;
    const T *exception;
} Except_Frame;

通过使用

typedef struct Except_Frame Except_Frame;

您正在将结构“ struct Except_Frame”重命名为“ Except_Frame”。

首先,键入Except_Frame而不是struct Except_Frame更为方便。 其次,在这种情况下,结构的字段“ Except_Frame * prev”将在编译时失败,因为编译器不熟悉名为“ Except_Frame”的结构(它熟悉名为struct Except_Frame的结构)

N,干杯

如果需要该typedef名称,那么实际上可以使用的两种流行的样式变体如下所示

typedef struct Except_Frame Except_Frame;
struct Except_Frame {
    Except_Frame *prev;
    ...
}; 

要么

typedef struct Except_Frame {
    struct Except_Frame *prev;
    ...
} Except_Frame;

注意与第二个变体的区别(原始的第二个变体甚至不会编译)。

现在,您要使用哪一个很大程度上取决于您的个人喜好。 第一个变量使类型名称的“简短”版本(仅Except_Frame )早于第二个变量。

首先,我们需要了解typedef的用法; typedef可用于指示变量如何表示某些内容;

typedef int km_per_hour ;
typedef int points ;

现在,就您的情况而言,您正在定义该结构,并希望它通过某种方式调用typedef。 我们需要在使用它之前预先定义它,因此我们在定义结构之前先声明

1  typedef struct Except_Frame t_Except_Frame;
2  struct Except_Frame {
3      t_Except_Frame *prev;
4      ...
5 }

第1行)现在,编译器了解到将存在名为“ struct Except_Frame”的结构,我们需要将def键入为“ t_Except_Frame”; 您是否注意到我为typedef添加了t_? 遵循这种做法是一种很好的做法,这样程序员可以很容易地了解到该值是typedef。

第3行)系统将其理解为结构Except_Frame的typedef变量,并相应地编译程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM