繁体   English   中英

2个相似typedef定义的差异

[英]Differences in 2 similar typedef definition

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

typedef struct
{
    int x, y;
} Point;

并以这种方式:

typedef struct Point
{
    int x, y;
};

有什么区别?

考虑下面给出的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);
 }

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

与此代码有什么不同:

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

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

暂无
暂无

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

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