结构实例和名称之间的区别

时间:2014-02-22 14:37:50

标签: c data-structures struct typedef

之间有什么区别
typedef struct complex {
    int x;
    int y;
};

typedef struct complex { 
    int x;
    int y;
} comp;

第二种情况中的额外comp有什么作用? 我尝试在第一种情况下定义complex类型的新变量,并在第二种情况下使用comp,两者都产生相同的结果......请帮忙!

4 个答案:

答案 0 :(得分:4)

第一个typedef没用,编译可能会给你一个警告。

在第二个typedef之后,每当您使用struct complex作为类型时,您都可以使用comp代替struct complex { int x; int y; }; typedef struct complex comp; 。您可以将第二个代码修改为此等效形式:

struct complex

您可以看到typedef定义了一种类型,而{{1}}则为其提供了另一种名称。

答案 1 :(得分:1)

typedef的目的是为由一个或多个类型组件组成的类型声明指定一个简单名称。

在第一个声明中,您不会为名为complex的结构指定任何名称。因此编译器将生成警告:

i.e. warning: declaration does not declare anything 

通常,当将typedef与结构[或联合]一起使用时,使用未命名的结构更好(更简洁),如:

typedef struct {int x; int y;} complex;

答案 2 :(得分:0)

struct complex {
    int x;
    int y;
} comp;

这是创建复杂类型变量的简写。 comp之前存在;所以它被视为complex.look ar类型的变量,代码也是

struct {
    int x;
    int y;
} comp;

您也可以使用创建其结构类型变量的旧编译器来执行此操作。

答案 3 :(得分:0)

长话短说:

struct complex {
    int x;
    int y;
};
// forces you to use :
struct complex c;

但是:

typedef struct complex {
    int x;
    int y;
} comp;
// allows you to use :
comp c;

Typedef只是一个可读性问题