roktim
roktim

Reputation: 81

What is the difference between typedef and enum

I am trying to use typedef and enum. I have got two lines.Is there any difference between two following lines ?

typedef enum {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE} STYPE

enum STYPE {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE}

Upvotes: 3

Views: 4391

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

  • First line defines an enum with no tag, and gives it a name STYPE
  • Second line defines a named enum called STYPE

The difference is that the first enum does not have an enum tag, while the second one does. In other words, both lines below will compile for enum STYPE

STYPE s1;
enum STYPE s2;

while only the first line will compile for the typedef enum ... STYPE.

Note: Using typedef is not common in C++, because enum defines a type name automatically. The construct is more common in C, where enum without typedef must be used only as a tag, i.e. with enum keyword. Finally, this construct is also used in C:

typedef enum STYPE {UNDEFINED, POINT2D, POINT3D, CIRCLE, SQUARE, RECTANGLE, SPHERE} STYPE;

It defines a tagged enum, and defines a type name for it. This declaration is also allowed in C++, but it is not different from your second declaration.

Upvotes: 5

Related Questions