RoR
RoR

Reputation: 16502

The use of enum without a variable name

I understand the first one but the second one? When and why would you do that?

enum cartoon { HOMER, MARGE, BART, LISA, MAGGIE };

enum { HOMER, MARGE, BART, LISA, MAGGIE };

Upvotes: 50

Views: 27311

Answers (5)

benjamin
benjamin

Reputation: 77

I am just providing a real life example use of anonyous enum, which I encountered in an embedded project. In the project, EEPROM is used to stored some parameters. Let's assume these parameters are those carton charater's ages, each parameter has the size of 1 byte in continuous address.

These parameters are copied into an array stored in ROM when the processor is powered on.

uint8_t ROM_AGE[END_AGE]

If we define an anomymous enum here:

enum { HOMER_AGE, MARGE_AGE, BART_AGE, LISA_AGE, MAGGIE_AGE, END_AGE };

Then the key words in enum can be used to index the age of each character like ROM_AGE[HOMER_AGE] . By using this enum, the readability is much better than using ROM_AGE[0].

Upvotes: 8

Jacob Relkin
Jacob Relkin

Reputation: 163308

This simply creates constant expressions that have the respective values, without a type other than simply int, so you can't use an unnamed enum as a type for anything, you will have to simply accept an int and then do comparison with the constant.

Something like this:

void doSomething(int c);

Versus something like this:

void doSomething(cartoon c);

By the way, your implementation would be the same, so in the case of unnamed enums, the only real drawback is strong typing.

Upvotes: 8

davka
davka

Reputation: 14692

you can define such enum in a class, which gives it a scope, and helps expose class's capabilities, e.g.

class Encryption {
public:
  enum { DEFAUTL_KEYLEN=16, SHORT_KEYLEN=8, LONG_KEYLEN=32 };
  // ...
};

byte key[Encryption::DEFAUTL_KEYLEN];

Upvotes: 40

icecrime
icecrime

Reputation: 76835

The second is an unnamed enum. I can be useful when you need the fields, but you don't intend to ever declare a variable of this enumeration type.

To provide a 'very C++' example of its use, you will often seen this in template metaprogramming where the enum is used as a 'compile time return value' without the intent of ever declaring a variable of this type :

template<class T>
struct some_metafunction
{
    enum { res = 0; };
};

Upvotes: 7

VGE
VGE

Reputation: 4191

enum, union, struct and class have a common part in the syntax share the same This unamed pattern is rarelly used. But sometime you may found this.

typedef enum { HOMER, MARGE, BART, LISA, MAGGIE } cartoont;

Or if you have a single variable containing only a few state.

enum { HOMER, MARGE, BART, LISA, MAGGIE } my_var;

This avoid the following declaration.

enum cartoon { HOMER, MARGE, BART, LISA, MAGGIE };
cartoon my_var;

Upvotes: 4

Related Questions