system
March 5, 2013, 10:19pm
1
I'm looking into protothreading: Arduino Playground - TimedAction Library
I understand for
for (First; Last; increment)
do while, and while loops.
I don't understand part of this bracket (from the example in the link above)
void blink(){
ledState ? ledState=false : ledState=true;
digitalWrite(ledPin,ledState);
}
I don't understand the layout of ledState ? ledState=false : ledState=true;
Translation:
ledState is true?
If yes, set it to false
If no, set it to true
This statement inverts true to false or false to true. I would rather say ledState=!ledState; where the ! means NOT.
That's the ternary operator:
boolean_value ? result_if_true : result_if_false;
They are using a round-about way of inverting the boolean value of ledState. The easy way is:
ledState = ! ledState;
They could also have used the operator more properly:
ledState = ledState ? false : true;
system
March 6, 2013, 12:14am
4
Thank you very much guys!
liudr & johnwasser
I understand now.
system
March 6, 2013, 12:18am
5
Xnor:
I don't understand the layout of ledState ? ledState=false : ledState=true;
Yeah, the person who coded that probably didn't understand it either. It's a misuse of the ternary operator and a very contrived way to invert a boolean.