Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why need typedef in the C++ enum definition [duplicate]

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

is that right?

like image 418
Adam Lee Avatar asked Dec 08 '22 15:12

Adam Lee


2 Answers

It's for C users. Basically when you go the typedef way, in C you can say

Test myTest;

whereas when you just used enum Test, you'd have to declare a variable like this:

enum Test myTest; 

It's not needed if only C++ is used though. So it might also just be written by a C programmer who is used to this style.

like image 51
Botz3000 Avatar answered Dec 11 '22 11:12

Botz3000


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

 enum Test{
    foo,
    bar
};
Test x;

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

 enum Test x;

or use the typedef.

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

like image 41
Bull Avatar answered Dec 11 '22 09:12

Bull