1

I was browsing a library for steppers motors when I ran across this line of foreign-looking code:

digitalWrite(enable_pin, (enable_active_state == HIGH) ? LOW : HIGH);

Is this some kind of shortcut to tossing an if statement into a function call? I've never seen this before. What exactly does it do, and what is this particular arrangement of code called?

Thanks!

2
  • 3
    Google something like "C++ ternary operator". There are many good explanations for that operator online
    – chrisl
    Aug 31, 2022 at 14:42
  • 2
    It could probably have been shortened to this instead: digitalWrite(enable_pin, ! enable_active_state ) ;
    – 6v6gt
    Sep 1, 2022 at 2:58

1 Answer 1

6

You could look at this as an "if expression", the correct term is "conditional operator" (C++ standard chapter 8.16). Many know it as "ternary operator" because it has three operands. You might already know the "unary operator" with one operand like the negation sign -x, or the "binary operator" with two operands like the addition a + b.

This expression consists of:

  • the first operand
  • the operator ?
  • the second operand
  • the operator :
  • the third operand

The first operator is evaluated and converted (if necessary) into a boolean.

If the result is true, the second operand is evaluated and gives the value of the expression.

If the result is false, the third operand is evaluated and gives the value of the expression.

Only one of the second and third operands is evaluated. This is important, if you use operands with side effects, like function calls can have.

This operator is often frowned upon. If used excessively, the source becomes easily unreadable. Many professional code style guide prohibit its use for this reason.

In your case it could have been written more clearly as

if (enable_active_state == HIGH) {
    digitalWrite(enable_pin, LOW);
} else {
    digitalWrite(enable_pin, HIGH);
}

It outputs the inverted value of the variable enable_active_state at the pin enable_pin.

Experienced Arduino users know that HIGH and LOW are represented in a way that are compatible with boolean values. Boolean inversions can be simpler expressed with the logical negation operator:

digitalWrite(enable_pin, !enable_active_state);

Anyway, the current compilers are commonly smart enough to generate the same machine code for each of the variants. Therefore, please write your source in the best way to express your intention. Anything else is "premature optimization", which is a bad thing. But this is a completely other topic.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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