Home > Blockchain >  Is this ? ternary operation legal?
Is this ? ternary operation legal?

Time:12-15

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 ?

CodePudding user response:

If it compiles, it is probably well-formed code. The compiler would issue an error message if the ternary operator could not be used with those operands on account of their type. The fact that there's no such error message suggests that there is no such problem with your code.

However, under some conditions, use of the ternary operator can result in possibly unintended copying.

If both the on and off methods return void (or, say, bool) there won't be any issue of copying, and the code will work as expected: if lockout[idx] is true then bulb[idx].off() will be evaluated, otherwise bulb[idx].on() will be evaluated. Only one of the two alternatives will be evaluated, just like what would happen with the if statement.

Generally, the ternary operator is used when you need the result to be an expression. Otherwise, writing the code using an if statement is usually more readable.

CodePudding user response:

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.

  • Related