[英]C structs vs typedef struct question
So my question is multifaceted. 所以我的问题是多方面的。
For the purpose of understanding C (not C++) I believe the following code: 为了理解C(不是C ++),我相信以下代码:
struct Foo { int bar; };
creates a custom type that I can use, but so does this: 创建一个我可以使用的自定义类型,但是这样做:
typedef Foo { int bar; };
The only difference I have seen is whether or not I have to use the "struct" keyword before the variable of the type Foo. 我所看到的唯一区别是我是否必须在Foo类型的变量之前使用“ struct”关键字。 What are the differences that cause this behavior?
造成此行为的差异是什么?
The difference is: 区别在于:
struct Foo { int bar; };
creates structure type { int bar; }
创建结构类型
{ int bar; }
{ int bar; }
named Foo. { int bar; }
名为Foo。 Ie full type name is struct Foo
. 即全名是
struct Foo
。
typedef Foo { int bar; };
creates alias Foo
for unnamed structure type { int bar; }
为未命名结构类型
{ int bar; }
创建别名Foo
{ int bar; }
However I'm not sure yours syntax is fully correct for strict C, but somehow it's OK for your compiler. 但是我不确定您的语法对于严格的C语言是完全正确的,但是对于您的编译器来说可以。 Or it creates something different, but accidentaly it works, C syntax can be very tricky.
或者它创建了一些不同的东西,但是偶然地它起作用了,C语法可能非常棘手。 Anyway second statement should be:
无论如何,第二个声明应该是:
typedef struct { int bar; } Foo;
For further reference you can use this . 为了进一步参考, 您可以使用this 。
struct
introduces a new type, but typedef
merely creates an alias for another type. struct
引入了一种新类型,但是typedef
仅为另一个类型创建别名。 This declaration creates a new type called struct Foo
: 该声明创建了一个称为
struct Foo
的新类型:
struct Foo { int bar; };
This declaration is simply invalid: 该声明完全无效:
typedef Foo { int bar; };
However, this declaration is valid, and creates a new, unnamed type, and also creates an alias to that type called Foo
: 但是,此声明有效,并创建了一个新的未命名类型,并且还为该类型创建了一个别名,称为
Foo
:
typedef struct { int bar; } Foo;
You can also create an alias to a named type - this creates an alias to the type struct Foo
called Foo
: 您还可以为命名类型创建别名-这为名为
Foo
struct Foo
类型struct Foo
创建别名:
typedef struct Foo Foo;
These two names are completely interchangeable - you can pass a struct Foo
to a function declared as taking an argument of type Foo
, for example. 这两个名称是完全可以互换的-例如,您可以将
struct Foo
传递给声明为采用Foo
类型参数的函数。
You can create aliases for any types, including built-in types. 您可以为任何类型(包括内置类型)创建别名。 For example, you can create an alias for
int
called Foo
: 例如,您可以为
int
创建一个名为Foo
的别名:
typedef int Foo;
I believe your syntax is incorrect. 我相信您的语法不正确。
typedef Foo { int bar; };
should be typedef Foo { int bar; } MyFoo;
应该是
typedef Foo { int bar; } MyFoo;
typedef Foo { int bar; } MyFoo;
The reason people would then use the typedef is so they can drop the struct in declarations. 人们之所以使用typedef是因为他们可以在声明中删除该结构。 Ie:
即:
struct Foo myFoo;
//vs.
MyFoo myFoo;
when i am going to compile this code 当我要编译这段代码时
typedef Foo { int bar; };
it says compile error 它说编译错误
error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.