typedef struct MyStruct MyStruct ;?

0

I am reading a book of design patterns and use the typedef in the following way. What would be the function in this case?

typedef struct MyStruct MyStruct;  

struct MyStruct {
  char var_1 ;
char var_2 ;
}
    
asked by ezeg 07.12.2018 в 23:28
source

1 answer

2

'typedef' is used to define an alias. For example:

typedef int tipo;

means that we can use 'type' as 'int' interchangeably. So that

tipo x;

is equivalent to creating an 'int' variable called x.

Therefore the sentence

typedef struct MyStruct MyStruct;

means that 'MyStruct' is equivalent to 'struct MyStruct'.

That way instead of defining variables like

struct MyStruct a;

we can do it in the abbreviated way

MyStruct a;

Anyway, the most usual way to combine 'typedef' and 'struct' is the following:

typedef struct MyStruct {
    char var_1;
    char var_2;
} MyStruct;

Note that what it does is define the 'struct MyStruct {...}' in addition to using 'typedef' to indicate that 'struct MyStruct' is equivalent to simply 'MyStruct'. It is equivalent to the code of your question but more compact.

    
answered by 28.12.2018 в 13:17