This question has already been answered:

What is the difference between a typedef struct / class and a custom type created using struct / class? Yes, I understand that typedef does not create a new type, but makes only an additional name for this type, but still, is it really so unprofitable to create a type? typedef:

typedef struct { int size; int * massive; } MyStr; 

Type of:

  struct MyStr{ int size; int * massive; }; 

Reported as a duplicate by Cerbo , αλεχολυτ c ++ Oct 31 '17 at 8:44 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Sample code add to the question. - αλεχολυτ
  • @alexolut, Added. - keoRez
  • In skillful hands, this piece shortens the length of the code, in inept ones it is an excellent way to confuse yourself and others, who then have to figure it out for a long time and what has been written here. - Alexander Muksimov

2 answers 2

In C ++ there is no difference, there is a difference in pure C. And in C ++ it is used rather as a relic of C. There are 4 types of namespaces in C language: 1) Labels (used in goto constructions) 2) Tags (names of structures, unions and enumerations) 3) Members of structures and unions 4) Everything else (names of functions, objects, constants and all typedefs) .

The C standard also requires ( C11 6.2.3 ) a separate namespace for each of these categories. Well, all compilers and IDE generally support this standard. That is, all these elements are created in different namespaces. Therefore, for example, such code

 struct myStruct {}; myStruct str; 

will not compile by the C compiler (but compiled by C ++), because the type myStruct is in a separate namespace (not the one in which the str variable is created). To make this code work, str should be declared like this:

 struct myStruct str; 

In order not to write the word struct before each variable declaration, you can use the method with typedef. Because Since everything that is declared via typedef is placed in a more general namespace (in the same as all other objects), now there is no need to write the word struct before each declaration.

  • I get it now. I often read program codes on the forums and it’s not rare that I meet data, lived, c ++ codes. - keoRez

Both of your examples are equivalent, they declare two different types of the same. Declarations in the form of typedef class/struct/union/enum come from C and are supported in C ++ for compatibility. Since a large number of old debugged libraries written in C.

  • As I recall, there were no classes in C, so the typedef class definitely not from there. - rudolfninja
  • @rudolfninja This is C ++ and the typedef ... declaration form typedef ... comes from C. Since C ++ allows you to declare classes, it is logical that this can be done in the form of typedef class - Cerbo
  • Is logical. Did not understand your idea correctly. I'm sorry. - rudolfninja