enum

Discussion in 'C++' started by Eric Beyeler, Nov 7, 2003.

  1. Eric Beyeler

    Eric Beyeler Guest

    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
     
    Eric Beyeler, Nov 7, 2003
    #1
    1. Advertising

  2. "Eric Beyeler" <> wrote in message
    news:...
    | 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
     
    Ivan Vecerina, Nov 7, 2003
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. -

    enum within an enum

    -, Jun 12, 2005, in forum: Java
    Replies:
    6
    Views:
    565
  2. Jerminia
    Replies:
    3
    Views:
    638
    Roedy Green
    Oct 7, 2005
  3. Ernst Murnleitner

    How to enum an enum?

    Ernst Murnleitner, Nov 12, 2003, in forum: C++
    Replies:
    5
    Views:
    485
    Rolf Magnus
    Nov 13, 2003
  4. mrhicks
    Replies:
    2
    Views:
    439
    Dave Thompson
    Jun 10, 2004
  5. Randy
    Replies:
    1
    Views:
    523
    David Harmon
    Jan 7, 2006
Loading...

Share This Page