Jump to content
  • Advertisement
Sign in to follow this  
The C modest god

Simple enum question

This topic is 5198 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

In C++ it is supposed to write enum{}name; without typedef before it, right? Then why when I write in an .h file enum, without typedef, in the .cpp file that includes that .h file it doesnt recognize this type (name). It only recognize it if I use typedef enum. So, what is the right way to do it?

Share this post

Link to post
Share on other sites
Indeed. What aaroncox1234 said is what you really want. When you have a name after enum {...}, what you are doing is declaring an anonymous enum type, and defining a variable of that type. So
} Identifier;

is creating an actual variable, named Identifier, of an anonymous enum type, that can contain the values One, Two, or Three. The same can be done with structs and classes. You can have an anonymous struct or class type, and immediately declare variables of that type.

In C, when you use the typedef method, typedef expects a type first of all, and then expects an identifier that will be now also use that type, so the identifier that is located at the end of enum {...} is an argument of the typedef expression. But without that typedef, that identifier actually gets interpretted as a definition of a variable instead.

Share this post

Link to post
Share on other sites
Using typedef when declaring enums and structs is a hack in C code to make it look more like C++.

Without typedef:
    struct Foo { ... };
enum Bar { ... };

struct Foo x;
enum Bar y;
With typedef:
    typedef struct Foo { ... } Foo;
typedef enum Bar { ... } Bar;

Foo x;
Bar y;
There is absolutely no reason to do this in C++. It can be annoying too, because you can't forward declare a typedef.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!