0

I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a kitchen timer.

In that code I found a statement

currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;

I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it. What does this statement mean?

1

Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.

if you do not understand ternary operators, it can be re-written as:

if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}

You should read up on the ternary operator. It appears in several languages in various formats and can come in handy in a variety of situations.

In general terms the ternary operator is of the following form (as used in an assignment):

result = (booleanExpression) ? (value if true) : (value if false);

but you can use it in other contexts for example in a function call:

someFn(booleanExpression ? trueValue : falseValue);
| improve this answer | |
  • 1
    does Internet need another ternary operator explanation? – Juraj Jul 5 '19 at 10:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.