Why is typedef needed in a C ++ enumeration definition?

I saw the following in the header file

typedef enum Test__tag { foo, bar } Test; 

I am wondering why using typedef; I can just use

 enum Test{ foo, bar }; 

- it is right?

+4
source share
2 answers

This is for C users. Basically, when you go the typedef path, in C you can say

 Test myTest; 

whereas when you just used enum Test , you would need to declare a variable like this:

 enum Test myTest; 

This is not necessary if only C ++ is used. So it can just be written by a C programmer who is used to this style.

+11
source

Yes, in C ++ you declare x without typdef, just by writing

  enum Test{ foo, bar }; Test x; 

However, if you were to try the same thing in C, you need to declare x as

  enum Test x; 

or use typedef.

So typedef is probably a habit left over from C (unless the header file is C).

+3
source

Source: https://habr.com/ru/post/1485388/


All Articles