2个相似typedef定义的差异

时间:2013-05-23 19:15:05

标签: c++ c struct typedef

您可以通过以下方式定义Point结构:

typedef struct
{
    int x, y;
} Point;

也是这样:

typedef struct Point
{
    int x, y;
};

有什么区别?

2 个答案:

答案 0 :(得分:1)

考虑下面给出的C代码,

typedef struct
{
    int x, y;
} Point;

int main()
{
  Point a;
  a.x=111;
  a.y=222;
  printf("\n%d %d\n",a.x,a.y);
}

上述代码将在没有任何错误或警告的情况下执行,而以下C代码会给您一个错误(error: 'Point' undeclared)和一个警告(warning: useless storage class specifier in empty declaration)。

typedef struct Point
{
    int x, y;
};

int main()
{
    Point a;
    a.x=111;
    a.y=222;
    printf("\n%d %d\n",a.x,a.y);
}

要更正错误,您已按如下方式声明结构变量a

 int main()
 {
    struct Point a;
    a.x=111;
    a.y=222;
    printf("\n%d %d\n",a.x,a.y);
 }

答案 1 :(得分:1)

第二个例子,typedef语句无效。编译器可能会忽略它或给你一个警告。

与此代码有何不同:

typedef struct Point
{
    int x, y;
} Point;

这允许您将Point用作类型或结构。我认为将结构名称用作类型,甚至作为变量是一种不好的做法,但是你可以这样做。