What does the "?" and ":" do in this Code

This is a variation of a blink with out delay .

  ms = millis();

  if (ms - msLast > (relayState ? Relay_ON : Relay_OFF))
  {
    digitalWrite(Relay, relayState = !relayState);
    msLast = ms;
  }

http://forum.arduino.cc/index.php?topic=201554.0
"Ternary operator"; a sort-of variation of an if/else statement that has a value.

relayState ? Relay_ON : Relay_OFF

if (relayState) then use Relay_ON otherwise use Relay_OFF

Useful shortcut once you get used to using it.

2 Likes

If you wrote a simple if statement like:

if (val == 10) {
   x = 20;
} else {
   x = 15;
}

You could write the same code using the ternary operator as:

x = (val == 10) ? 20 : 15;

If the conditional expression (val == 10) is True, the expression following the question mark is evaluated. If the conditional expression is False, the expression following the colon is evaluated.

5 Likes

It can also be used as a general if/else as well, discarding any return value (if any):

(val > 4) ? do_something() : do_something_else();

econjack:
If you wrote a simple if statement like:

if (val == 10) {

x = 20;
} else {
   x = 15;
}



You could write the same code using the ternary operator as:



x = (val == 10) ? 20 : 15;




If the conditional expression (val == 10) is True, the expression following the question mark is evaluated. If the conditional expression is False, the expression following the colon is evaluated.

This is where I'd have gone ...

"No, Mr Engineer Sir.... NO NO NO NO NO NOOOOOO"

 if (x ==10) {?=20 else 15};

would make more sense...

Thanks for posting this. I put it in my 'Cool Code" folder. The part of the code I still don't understand is the > operator.

if (ms - msLast > (relayState ? Relay_ON : Relay_OFF))

Just what is the result of 'ms-msLast' being compared to?

  • Scotty

Just what is the result of 'ms-msLast' being compared to?

Either "Relay_ON" or "Relay_OFF", depending on the value of "relayState"

Thanks for the replies, it makes more since now.
The ms is milli seconds
The ms Last is milli seconds last

Just like blink without delay.

This way I can use conditions to vary the on and off duration and the on and off don't have to be the same duration like blink with out delay.

Really cjdelphi?

How do I know what variable gets assigned to in your syntax?
What if you want to assign to a variable that doesn't show up anywhere else in the expression?

i.e.

y = (x>10)?(30):(40);

Your syntax is the one that makes no sense.