[英]Differences in 2 similar typedef definition
You can define a Point struct in this way: 您可以通过以下方式定义Point结构:
typedef struct
{
int x, y;
} Point;
and also in this way: 并以这种方式:
typedef struct Point
{
int x, y;
};
What is the difference? 有什么区别?
Consider the C
code given below, 考虑下面给出的
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);
}
The above code will execute without any errors or warnings, whereas the following C
code will give you an error ( error: 'Point' undeclared
) and a warning ( warning: useless storage class specifier in empty declaration
). 上面的代码将在没有任何错误或警告的情况下执行,而以下
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);
}
To correct the error you have declare the structure variable a
as follows, 要更正错误,您已声明结构变量
a
,如下所示,
int main()
{
struct Point a;
a.x=111;
a.y=222;
printf("\n%d %d\n",a.x,a.y);
}
The second example, the typedef
statement have no effect. 第二个例子,
typedef
语句没有效果。 The compiler will probably ignore it or give you a warning. 编译器可能会忽略它或给你一个警告。
What differs from this code: 与此代码有什么不同:
typedef struct Point
{
int x, y;
} Point;
This allow you to use Point as a type, or as a struct. 这允许您将Point用作类型或结构。 I consider a bad practice to use the struct name as a type, or even as a variable, but you are allowed to do this.
我认为将结构名称用作类型,甚至作为变量是一种不好的做法,但您可以这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.