small medium large xlarge

Back to: All Forums  Arduino
27 Feb 2011, 01:18
Robert Ralston (2 posts)

Printed book, P1.0, Page 58, code line 15:

 led_state = (led_state == LOW) ? HIGH : LOW;

I don’t understand this line. It is meant to toggle led_state. But I’m not familiar with either the “?” or the colon between HIGH and LOW.


27 Feb 2011, 06:06
Steven Guitar (4 posts)

Robert, this is a ternary operator common to various programming languages. basically, it works like

(condition) ? if_true : if_false

it is shorthand for something more complicated like

if(condition == true) {
   //do this
} else {
   // do this instead

so, what happens here is that the led state gets the value of HIGH if the led_state equals LOW, and if the led_state currently is != LOW, the led_state will be come LOW. the effect is that if its LOW, we now set it to HIGH. if its HIGH, we will set it to LOW thus toggling the value of led_state.

28 Feb 2011, 03:18
Robert Ralston (2 posts)

Steven, thanks very much. Elegant shorthand. I’ll be using that.

I was unable to find that operator on the Arduino Reference page. If it really isn’t there, then perhaps I’m missing out on other elegant coding options and should get a C++ book.


You must be logged in to comment