What's the difference between

typedef struct LINE { .... }; 

and

 struct LINE { ... }; 

2 answers 2

In your example, there is no difference, the typedef simply ignored. If we rewrite this code a bit:

 typedef struct LINE { } alias; 

That structure object can be created both with LINE and alias , since typedef creates type aliases.

  • In this case alias will be a pseudonym? - neko69
  • four
    @ neko69, yes, but you can choose any other name or even several names (separated by commas) - ixSci

typedef used to create aliases for other data types. The given example is better corrected, for example:

 typedef struct LINE { ... } t_line; 

typedef can be used not only for structures, but also for any other types:

 typedef int t_message_id; typedef enum e_Colour {...} t_colour; 

The main reasons for using typedef ads

Reduce data type names to improve readability and ease of typing. In the example above, without using a typedef will have to write a struct LINE . In C ++, this problem is solved (you can just write LINE ), however long type names can be used, for example: std::vector<LINE>::size_type can be abbreviated using typedef ... t_lvecsz .

Abstraction from the data type used in this implementation to facilitate possible implementation changes. For example, a struct LINE could be declared like this:

 struct LINE { float x1,y1,x2,y2; }; 

and the rest of the code uses the float type to represent the coordinates. When a transition arises, for example, to the double type, you will need to make many changes to the code (and, as always, forget to make changes somewhere). This problem is well solved with the help of the following announcements:

 typedef float t_coord; struct LINE { t_coord x1,y1,x2,y2; }; 

Also typedef can be used to facilitate the creation of complex type declarations (something like "an array of pointers to functions that return a pointer to a structure, etc.").

  • Only "new types" are better named, adding not t_ to the beginning, but _t to the end. Look at all these time_t , pid_t , int32_t , etc. - avp
  • @avp The _t suffix is ​​reserved by the standard and it is better not to use it in its programs. - Konstantin Les
  • 2
    @KonstantinLes, can I link to the standard? I do not remember such a reservation for him - ixSci
  • @ixSci Yes, you are right. The standard reserves only uintXXX_t and intXXX_t. Somewhere I read about it (probably, at Golub). Well, in general, the whole logic of the development of the standard confirms this. This topic is discussed here: stackoverflow.com/questions/231760/… - Konstantin Les
  • @KonstantinLes, apparently it largely depends on how you evaluate your own programs. By the way, I absolutely did not mean that in each typedef you have to push _t or t_ . - avp