Sign in to follow this  
Striken

[Solved] C++ Enumerations

Recommended Posts

Striken    110
Hi all, quick basic question! How are enumerations handled by the compiler in C++? Since a (equivalent?) C approach is to use a list of preprocessor defines, I was wondering if enumerations were treated essentially the same as defines, and their literal values moved in to replace their identifier by the preprocessor before the program is compiled? Are there any drawbacks (storage) on using enums? Cheers! [Edited by - Striken on December 14, 2006 9:49:50 AM]

Share this post


Link to post
Share on other sites
ToohrVyk    1595
In both C and C++, enumeration literals are replaced with their value by the compiler (not the preprocessor). C++ enforces enumeration types (casting from an integer to an enumeration must be explicit) while C doesn't. As for storage, the compiler will always use the best possible storage (taking into account both the set of allowed values and alignment requirements).

Share this post


Link to post
Share on other sites
Aardvajk    13207
Also since, as Toohvyk mentions, the enum types are enforced in C++, an enumeration will cause a different function signature from the point of view of function overloading:


enum Day { Mon,Tue,Wed };

void Print(int I);
void Print(Day D);

int main()
{
Print(10); // calls the first one
Print(Mon); // calls the second one
}


Type enforcing like this is a fundamental difference between a C++ named enumeration and a #define or even a const int x=whatever. The above overloading is of one particular use when it comes to streams:


ostream &operator<<(ostream &o,Day d)
{
switch(d)
{
case Mon: os << "Monday"; break;
// etc
}

return os;
}

int main()
{
Day day=Mon;

cout << "The day is " << d << endl;
}


You couldn't get this behaviour without the compiler considering a named enumeration to have a distinct type.

I doubt there are any storage drawbacks since, given that enum values are constant, the compiler would be free to insert their immediate values into generated code rather than have to store them in an executable as data, so in that sense there is no difference between an enum and a #define.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this