Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > enum

Reply
 
 
Eric Beyeler
Guest
Posts: n/a
 
      11-07-2003
I ran into an interesting characteristic of enums... why is comparison
between different types allowed? assignment is not allowed ( which I
would expect )

enum TESTA
{
TestA1=4,
TestA2=5,
};

enum TESTB
{
TestB1=7,
TestB2=8,
};

int main()
{
TESTA a;
a = TestA2;
TESTB b;
b = TestB2;
//a = TestB2; // not allowed
if (a == b) // why is this legal?
{
}
if ( a == TestB2 ) // why is this legal?
{
}
}

Eric B
 
Reply With Quote
 
 
 
 
Ivan Vecerina
Guest
Posts: n/a
 
      11-07-2003
"Eric Beyeler" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) m...
| I ran into an interesting characteristic of enums... why is comparison
| between different types allowed? assignment is not allowed ( which I
| would expect )

For historical reasons, enums are implicitly converted to an
integral value whenever needed. And there always is an
integral value to represent any enum value.
So when you compare two enum values, they are both converted
to an integer.

However, assignment of an int to an enum variable leads
to undefined behavior if the enum is not large enough
to store the integral value.
For example:

| enum TESTA
| {
| TestA1=4,
| TestA2=5,
| };

void f(int i)
{
TESTA e = i; // what if i is out of range?
}

So, allowing the assignment of any integer, without casting,
to a variable of enum type, would be worse than the opposite.

This said, the compiler will not complain if you try to
assign a 'long' to a 'short', so things aren't too consistent
here either ...


Regards,
Ivan
--
http://ivan.vecerina.com


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
ENUM server for private ENUM kael UK VOIP 2 02-25-2007 11:54 AM
enum: display elements of an enum specified at runtime Jerminia Java 3 10-07-2005 10:08 PM
enum within an enum - Java 6 06-13-2005 12:51 AM
Including an enum within another enum, possible? mrhicks C Programming 2 06-10-2004 03:00 AM
How to enum an enum? Ernst Murnleitner C++ 5 11-13-2003 11:06 AM



Advertisments