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 ;
}
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 ;
}
'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.