I'm no expert, but I do like to learn and understand. With that in mind I wrote the following in the Arduino IDE:
lockout[idx] ? bulb[idx].off() : bulb[idx].on();
to replace this:
if (lockout[idx]) bulb[idx].off(); else bulb[idx].on();
lockout[]
is an array of bool
, and bulb[]
is an array of a class, with .off
and .on
methods.
I've looked around for examples and never seen this usage of the ?
ternary operator. And what I've read seems to say that this should not work.
But it does compile. So is this in fact legitimate C++?
Yes, this is legitimate C++. While that operator is commonly called the ternary operator, it is called the conditional operator in the C++ standard, and it is defined in the section named "expr.cond".
The C++ standard explicity says it is OK for both the second and third operands to have type void
. So the standard writers knew that people might want to use this operator as a short way to write if
statements, like you are doing.
If the types of the second or third operands are not void
, then the standard says "an attempt is made to convert each of those operands to the type of the other" and it goes into detail about what that means.
For reference, the version of the C++ standard I am referring to is N4296, so it's a little old but I don't think that matters.