2

I recently came across this piece of code and I'm wondering why it works. Enum declaration:

enum BuildResult {
    RESULT_ERROR,
    RESULT_SUCCESS
};

Later, this Enum is used in an if statement (ignore the fact that it could instead be RESULT_ERROR):

if (!objectHere->build_result == ClassNameHere::RESULT_SUCCESS)

I was not aware that you could use the not operator ! to flip the value of an Enum. Does this only work with Enums that have two states? Are there other kinds of implicit operators that can be used with Enums? I did find this question about manually declaring operators, but it doesn't seem to mention any implicit operators for enums.

Aaron Franke
  • 3,268
  • 4
  • 31
  • 51

1 Answers1

5

The enum is implicitly casted to bool. When you flip it, it is no longer an enum type, but a boolean pr-value.

If you replace enum with enum class, which is type safe, this conversion is no longer possible.

When simple enum declaration is used, enum rvalues behave exactly like integers. You can even specify the type of the integer:

enum myEnum : uint32_t { NOT, TYPE, SAFE };

(note the implicit values of an enum: {NOT=0, TYPE=1, SAFE=2})

Kostas
  • 4,061
  • 1
  • 14
  • 32
  • 2
    To extend the answer: This does actually work with enums that have more than 2 states. In a normal enum, every value corresponds to an integral value. In this case RESULT_ERROR is 0, and RESULT_SUCCESS is 1. Since there is an implicit conversion from int to bool, this works with every other operator, too. You can use mathematical operators, as well as logical operators on the bools. But they won't make much sense for more than two states, because everything except the one defined as 0 will evaluate to true. – birdfreeyahoo Oct 06 '18 at 06:16