468,780 Members | 2,166 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,780 developers. It's quick & easy.

enum

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
Jul 19 '05 #1
1 5314
"Eric Beyeler" <eb********@yahoo.com> wrote in message
news:8c*************************@posting.google.co 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
Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

20 posts views Thread by Glenn Venzke | last post: by
21 posts views Thread by Andreas Huber | last post: by
31 posts views Thread by Michael C | last post: by
18 posts views Thread by Visual Systems AB \(Martin Arvidsson\) | last post: by
2 posts views Thread by Dennis | last post: by
1 post views Thread by Randy | last post: by
2 posts views Thread by Randy | last post: by
34 posts views Thread by Steven Nagy | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
2 posts views Thread by Marin | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.