enum without name

Dear all,

Reading some codes, I realize the following code:
1
2
  enum {On, Off};
  enum {SZ=80};

Can you please, explain the meaning of them. I only know the way as:
 
  enum Status {On, Off};

By this way, we define a new datatype Status ranges from On to Off.

Thank you.
The first snippet are anonymous enums. They do not create new types. You lose the type safety of named enums.

1
2
  enum foo = Off;  
  foo = SZ;  // Valid because neither enum is typed.  

> The first snippet are anonymous enums. They do not create new types.

They do create distinct new types.

(However, the type of an unnamed enumeration does not have a name; its type can be accessed with the keyword decltype or deduced via type deduction.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <type_traits>

int main()
{
    enum { X = 78 }; // X has a distinct (unnamed) type
    enum { Y = 79 }; // Y has a distinct (unnamed) type
    
    // X and Y are of two different types 
    std::cout << "X and Y are of the same type? " << std::boolalpha
              << std::is_same< decltype(X), decltype(Y) >::value << '\n' ; // false

    const auto ex = X ;
    auto ey = Y ;
    
    // ey = ex ; // *** error: ex and ey are of different types with no implicit conversion between them
    // ey = int(ex) ; // *** error: no implicit conversion from int to type of ey
    // ey = 7 ; // *** error: no implicit conversion from int to type of ey

    using type_of_y = decltype(Y) ;
    ey = type_of_y(ex) ; // fine: explicit conversion with a cast
    ey = type_of_y(7) ; // fine: explicit conversion with a cast
    
    std::cout << ey << ' ' << (X==Y) << '\n' ; // fine: implicit conversion to the underlying type 'int'
                                               // g++: ** warning: (X==Y) comparison between unrelated enum types
}

http://coliru.stacked-crooked.com/a/7a16f2e63eef47e7
Thanks for the correction.
Topic archived. No new replies allowed.