0
enum segment
{
  OFF,
  ON
};

int main()
{
  segment indicator;
  int temp_prev = 37;
  int temp_curr = 39;
  indicator = OFF;

  if ((temp_curr > temp_prev and temp_curr > 39) or !indicator)
  {}

This is part of a basic program to understand the use and properties of enum.

What confuses me is, what does !enum return, and what will the if condition return?

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Paris
  • 5
  • 2
  • 2
    Here's a description of [how `enum`s start at zero](https://stackoverflow.com/a/34811571/1270789), so effectively `OFF` is zero and `ON` is one. However, using an `enum` as a boolean is confusing; I'd recommend `bool indicatorIsOn;` as a better naming. – Ken Y-N Jun 12 '20 at 02:38
  • Your code is not a good [mre]. and an optimizing C++ compiler is allowed to transform it into an empty `main`. Read e.g. [n3337](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf) – Basile Starynkevitch Jun 12 '20 at 03:51

2 Answers2

1

what confuses me is what does !enum return

Unary ! is the logical NOT operator. The enum value implicitly converts to the underlying integer type. The result is true if that integer is 0, and false otherwise. The underlying value of OFF is 0, therefore the result is true in this case, and so is the entire condition.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
eerorika
  • 232,697
  • 12
  • 197
  • 326
1

(Assuming C) An enum is stored as an int. In your example, OFF would default to zero, which is treated as false in a conditional, any non-zero value would be considered true.

Danny Parker
  • 1,713
  • 18
  • 30