简体   繁体   中英

C structs vs typedef struct question

So my question is multifaceted.

For the purpose of understanding C (not C++) I believe the following code:

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. What are the differences that cause this behavior?

The difference is:

struct Foo { int bar; }; 

creates structure type { int bar; } { int bar; } named Foo. Ie full type name is struct Foo .

typedef Foo { int bar; };

creates alias Foo for unnamed structure type { int bar; } { int bar; }

However I'm not sure yours syntax is fully correct for strict C, but somehow it's OK for your compiler. Or it creates something different, but accidentaly it works, C syntax can be very tricky. Anyway second statement should be:

typedef struct { int bar; } Foo;

For further reference you can use this .

struct introduces a new type, but typedef merely creates an alias for another type. This declaration creates a new type called 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 :

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 :

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.

You can create aliases for any types, including built-in types. For example, you can create an alias for int called 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;

The reason people would then use the typedef is so they can drop the struct in declarations. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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