Partager via


Operators and Enumerations 

This topic discusses the operators that are valid on a managed enum.

Remarks

The following operators are valid on enums:

Operator

== != < > <= >=

+ -

^ & ~

++ --

sizeof

Operators ^ & ~ ++ -- are defined only for enumerations with integral underlying types, not including bool. Both operands must be of the enumeration type.

The compiler does no static or dynamic checking of the result of an enum operation; an operation may result in a value not in the range of the enum's valid enumerators.

Example

// mcppv2_enum_5.cpp
// compile with: /clr
enum class E { a, b } e, mask;
int main() {
   if ( e & mask )   // C2451 no E->bool conversion
      ;

   if ( ( e & mask ) != 0 )   // C3063 no operator!= (E, int)
      ;

   if ( ( e & mask ) != E() )   // OK
      ;
}

// mcppv2_enum_6.cpp
// compile with: /clr
enum class day : int {sun, mon};
enum : bool {sun = true, mon = false} day2;

int main() {
   day a = day::sun, b = day::mon;
   day2 = sun;

   System::Console::WriteLine(sizeof(a));
   System::Console::WriteLine(sizeof(day2));
   a++;
   System::Console::WriteLine(a == b);
}

Output

4
1
True

See Also

Reference

enum class