• Advertisement
Sign in to follow this  

[Solved] C++ Enumerations

This topic is 4086 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

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
Advertisement
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
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
Sign in to follow this  

  • Advertisement