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

Simple enum question

This topic is 4831 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
Advertisement
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
enum
{
One,
Two,
Three
} 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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!