What is the difference between `typedef struct X {}` and `typedef struct {} X`?

What is the difference between these two declarations in C:

typedef struct square{ //Some fields }; 

and

 typedef struct{ //Some fields } square; 
+5
source share
2 answers

First announcement:

 typedef struct square { // Some fields }; 

defines a type called struct square . The typedef keyword is redundant (thanks to HolyBlackCat for pointing this out). This is equivalent to:

 struct square { //Some fields }; 

(The fact that you can use the typedef keyword in a declaration without specifying a type name is a failure in C.'s syntax.)

This first announcement probably should have been:

 typedef struct square { // Some fields } square; 

Second announcement:

 typedef struct { // Some fields } square; 

defines an anonymous type struct and then gives it an alias of square .

Remember that typedef alone does not define a new type, but only a new name for an existing type. In this case, the definition of typedef and the (anonymous) struct are combined into a single declaration.

+10
source
 struct X { /* ... */ }; 

Create a new type. So you can declare this new type

 struct X myvar = {...} 

or

 struct X *myvar = malloc(sizeof *myvar); 

typdef is used to indicate type

 typedef enum { false, true } boolean; boolean b = true; /* Yeah, C ANSI doesn't provide false/true keyword */ 

So you renamed enum to boolean.

So when you write

 typedef struct X { //some field } X; 

You rename the struct X structure to X. When I said rename, it is more a different name.

Tips, you can simply write:

 typedef struct { //some field } X; 

But if you need a field with the same type (for example, in a linked list), you had to specify the name of your structure

 typedef struct X { X *next; /* will not work */ struct X *next; /* ok */ } X; 

Hope this helps :)

Edit: As Kate Thompson said, typdef is for creating an alias :)

+2
source

Source: https://habr.com/ru/post/1206130/


All Articles