Go Down

Topic: Protothreading (Read 381 times) previous topic - next topic

Xnor

I'm looking into protothreading: http://playground.arduino.cc/Code/TimedAction#Example

I understand for
Code: [Select]
for (First; Last; increment)
do while, and while loops.


I don't understand part of this bracket (from the example in the link above)
Code: [Select]
void blink(){
  ledState ? ledState=false : ledState=true;
  digitalWrite(ledPin,ledState);
}


I don't understand the layout of 
Code: [Select]
ledState ? ledState=false : ledState=true;

liudr

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.

johnwasser

That's the ternary operator:

Code: [Select]
    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:

Code: [Select]
   ledState = ! ledState;

They could also have used the operator more properly:

Code: [Select]
    ledState = ledState ? false : true;
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Xnor

Thank you very much guys!
liudr & johnwasser
I understand now.

PeterH


I don't understand the layout of 
Code: [Select]
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.
I only provide help via the forum - please do not contact me for private consultancy.

liudr

http://en.wikipedia.org/wiki/Obfuscated_code

Maybe?

Go Up