Home c++ Why do you need a typedef?

Why do you need a typedef?




What’s the difference between

typedef struct LINE


struct LINE

Answer 1, authority 100%

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

typedef struct LINE
} alias;

Then the structure object can be created using both LINE and alias , since typedef creates type aliases.

Answer 2, authority 93%

typedef is used to create aliases for other data types.
It is better to correct the above example, 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;

Top reasons for using typedef declarations

Abbreviated data type names to improve readability and ease of typing. In the above example, without using typedef , you would have to write struct LINE . C++ solves this problem (you can just write LINE ), however, long type names can be used, for example: std :: vector & lt; LINE & gt; :: size_type can be shortened with typedef ... t_lvecsz .

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

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

and throughout the rest of the code, the float type is used to represent coordinates. If you need to switch, 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 following declarations:

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, returning a pointer to a structure, etc.”).

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions