Do enum values behave like global variables?

It's not treated as a global variable. It's treated as a global identifier.

More precisely, it's treated as an identifier in whatever namespace the enum is declared in. In your case, that's the global namespace.

For an idea of what the difference is between a global identifier and a global variable, try taking the address of your enum. ;)

Usually when I define enums, I prepend the an abbreviated version of the name of the identifier. Like this:

enum InstrumentType { itStock, itEquityOption, itFutureOption };

This helps to avoid collisions.


Wyatt Anderson has already suggested

namespace A
{
    enum A {joe, bob, doc};
}
namespace B
{
    enum B {sunday, monday, doc};
}

as a fix for the "enum values are in the same scope as the enum itself" problem, allowing you to write

A::doc;
B::doc;

But this solution is not available when you want an enum local to a class, at least not without introducing an artificial namespace outside the class.

A simple solution is to instead wrap each enum in a struct, like so:

struct A
{
    enum Enum {joe, bob, doc};
};
struct B
{
    enum Enum {sunday, monday, doc};
};

This allows the same usage notation as with the namespace solution,

A::doc;
B::doc;

but it additionally allows

  • definition within a class,

  • bringing the enumeration names directly into a class via inheritance, and

  • local-in-class renaming of the qualifier, via typedef.

Plus, the naming convention exemplified above allows

  • in my view, a little extra clarity when referring to an enum type, e.g. writing A::Enum.

OK, the naming convention can also be used with the namespace based solution…

Cheers & hth.,


Enumerators in C++03 have the same scope as the enumeration .

enum     xxx    {    yyy,       zzz       };
          ^           ^          ^ 
    enumeration    enumerator enumerator

This is sometimes convenient, sometimes not really.

In C++0x we will have enum classes which are more like C#'s enums. In the meantime, just assume (cause that's the language rule) that yyy and zzz have exactly the same scope as xxx

Tags:

C++

Enums